Re: which is more 'pythonic' / 'better' ?

2005-09-12 Thread Steven Bethard
Steven D'Aprano wrote: > try...except... blocks are quick to set up, but slow to catch the > exception. If you expect that most of your attempts will succeed, then the > try block will usually be faster than testing the length of the list > each time. > > But if you expe

Re: make sure entire string was parsed

2005-09-12 Thread Steven Bethard
Steven Bethard wrote: > Paul McGuire wrote: > >>>> I have to differentiate between: >>>> (NP -x-y) >>>> and: >>>> (NP-x -y) >>>> I'm doing this now using Combine. Does that seem right? >> >> >> If your wor

Re: How to protect Python source from modification

2005-09-12 Thread Steven D'Aprano
their IT department, precisely as it would be if they gave full read/write permission to everyone in the company instead of restricting permissions to those who need them. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: How to protect Python source from modification

2005-09-12 Thread Steven D'Aprano
y need your program to do it. -- Steven -- http://mail.python.org/mailman/listinfo/python-list

Re: make sure entire string was parsed

2005-09-13 Thread Steven Bethard
Paul McGuire wrote: > I still don't know the BNF you are working from Just to satisfy any curiosity you might have, it's the Penn TreeBank format: http://www.cis.upenn.edu/~treebank/ (Except that the actual Penn Treebank data unfortunately differs from the format spec in a few ways.) > 1. I'm s

Re: Simplifying imports?

2005-09-13 Thread Steven D'Aprano
r design. eg if you have a good reason for requiring one class per file, then one possible work around would be to define a single "header" module containing all those "from foo.Bar import Bar" statements, and then in your actual module(s) call "from header import *". Watch out for circular imports though. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: which is more 'pythonic' / 'better' ?

2005-09-13 Thread Steven Bethard
Peter Hansen wrote: > def meth(self, things=None): > self.things = things or [] > [snip] > > The alternative is fine too, but insisting on it would be pedantic, and > if you have more than one of these it is definitely less readable (and, > therefore, not Pythonic): > > def meth(self, thin

Re: Software bugs aren't inevitable

2005-09-14 Thread Steven D'Aprano
w try the 50th. (Warning: the amount of work done by the recursive version increases at the same rate as the Fibonacci sequence itself increases. That's not quite exponentially, but it is fast enough to be very painful.) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Removing duplicates from a list

2005-09-14 Thread Steven D'Aprano
' which must make a pass through every element of the list, which > would be slower than the efficient hashing that set does. But count passes through the list in C and is also very fast. Is that faster or slower than the hashing code used by sets? I don't know, and I'll bet you d

Re: Software bugs aren't inevitable

2005-09-14 Thread Steven D'Aprano
On Wed, 14 Sep 2005 11:28:02 -0400, Terry Reedy wrote: > > "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> Which works wonderfully as an academic exercise, but doesn't tend to work >> so terribly well in the r

Re: Software bugs aren't inevitable

2005-09-14 Thread Steven D'Aprano
n (b,a+b) Ah, I like this algorithm! I'll add it to my collection. Thank you. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Example Script to parse web page links and extract data?

2005-09-14 Thread Steven Bethard
livin wrote: > I'm looking for an easy way to automate the below web site browsing and pull > the data I'm searching for. This is a task that BeautifulSoup[1] is usually good for. > 4) After search, table shows many links (hundreds sometimes) to the actual > data I need. > Links are this fo

Re: Removing duplicates from a list

2005-09-14 Thread Steven Bethard
przemek drochomirecki wrote: > def unique(s): > e = {} > for x in s: > if not e.has_key(x): >e[x] = 1 > return e.keys() This is basically identical in functionality to the code: def unique(s): return list(set(s)) And with the new-and-improved C implementation of sets comin

Re: python-dev Summary for 2005-08-01 through 2005-08-15

2005-09-14 Thread Steven Bethard
Steve Tregidgo wrote: > on 2005-08-30 01:45 Tony Meyer said the following: > >> [The HTML version of this Summary is available at >> http://www.python.org/dev/summary/2005-08-01_2005-08-15.html] > ... >> Many revision control systems were extensively discussed, including >> `Subversion`_ (SVN), `P

Re: Software bugs aren't inevitable

2005-09-15 Thread Steven D'Aprano
On Wed, 14 Sep 2005 12:23:00 -0700, Paul Rubin wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: >> It is a "mere implementation detail" that (for most computer systems, and >> most programming languages) stack space is at a premium and a deeply >> rec

Re: Software bugs aren't inevitable

2005-09-15 Thread Steven D'Aprano
ogramming languages that optimize your recursion, and most programmers don't have the skills to do it themselves. That is a skill, and not one that is taught in terribly many "Python in a Nutshell" style books. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Software bugs aren't inevitable

2005-09-15 Thread Steven D'Aprano
t. In hindsight, I should have reworded my post to be more clear. I am not opposed to recursion itself, just overly broad advice that recursion is always good and modifying variables is always bad. [snip] > And here the recursion limit won't get you!! But the memoization > te

Re: Software bugs aren't inevitable

2005-09-16 Thread Steven D'Aprano
On Thu, 15 Sep 2005 18:07:28 +0100, phil hunt wrote: > On Thu, 15 Sep 2005 21:56:06 +1000, Steven D'Aprano <[EMAIL PROTECTED]> wrote: >> >>Are you saying that the recursion done by "serious" languages is a fake? >>That it is actually implemented behind th

Re: How to clear screen in Python interactive shell mode?

2005-09-16 Thread Steven D'Aprano
"ce"): # DOS/Windows os.system('CLS') else: # Fallback for other operating systems. print '\n' * numlines -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Removing duplicates from a list

2005-09-16 Thread Steven Bethard
drochom wrote: > i suppose this one is faster (but in most cases efficiency doesn't > matter) > def stable_unique(s): > > e = {} > ret = [] > for x in s: > if not e.has_key(x): > e[x] = 1 > ret.append(x) > retur

Re: complex data types?

2005-09-17 Thread Steven D'Aprano
7;]} # Store it in the album list. albums.append(album) You can change an item like this: # Oops, wrong artist... albums[0]["artist"] = "beatles" albums[0]["songlist"].append("mean mr mustard") Does this solution work for you? If not, what does it not do that you need it to do? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Steven D'Aprano
On Sun, 18 Sep 2005 03:46:03 -0700, Xah Lee wibbled: > Can anyone tell me what this verbiage is trying to fucking say? Please don't feed the trolls. In other words, if everybody ignores this loser, he might crawl back under the rock he came from. -- Steven. -- http://mail.python.org

Re: Putting a lock on file.

2005-09-18 Thread Steven D'Aprano
int "Sorry, the file is in use. Please try again later." return None You should look at the module errno, together with the function os.strerror(), for more details. Of course, many people don't worry about giving their own explanations for IOErrors, and simply return the sa

Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Steven D'Aprano
e the file, that specifies the end-of-file. You might find the truncate() method useful: f=open('mytext.txt','w+') f.write('My name is Bob') f.truncate() s = f.read() # s should be the empty string -- untested because I'm not running Windows f.seek(0) s = f.read() # s should be "My name is Bob" f.close() Hope this helps. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Question About Logic In Python

2005-09-19 Thread Steven D'Aprano
convert it into a bool. Are there any other uses for bool()? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Twist and perversion. Was: Software bugs aren't inevitable

2005-09-19 Thread Steven D'Aprano
one of a hundred other programming patterns. The more tools you have, the more likely you will find one that works for your particular problem. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: C#3.0 and lambdas

2005-09-19 Thread Steven D'Aprano
s a can of worms, what happens if you pass a mutable object like a list instead of a tuple or string? Still, if Python is eventually to get something static types, it probably makes sense to keep the def func((x,y)) idiom, because it will come in handy for ensuring that your sequence argument

Re: C#3.0 and lambdas

2005-09-19 Thread Steven Bethard
Paul Rubin wrote: > "Fredrik Lundh" <[EMAIL PROTECTED]> writes: > >>"Is anyone truly attached to nested tuple function parameters; >>'def fxn((a,b)): print a,b'? /.../ >> >>Would anyone really throw a huge fit if they went away? I am willing >>to write a PEP for their removal in

Re: C#3.0 and lambdas

2005-09-19 Thread Steven Bethard
Steven D'Aprano wrote: > Consider this: > > def func(some_tuple): > > How many items should you pass in the tuple? If it takes variable > arguments, then that works, but if you always expect a fixed number, then > > def func((x, y)) > > is more explicit. &

Re: Why is map() preferable in this case?

2005-09-19 Thread Steven Bethard
Delaney, Timothy (Tim) wrote: > Devan L wrote: > >>Map is in C. It's faster, but not as clear. Some people do think >>map(f, L) is nicer though. Google is your friend here, if you want to >>read the old arguments. > > map() will be faster if the function you are calling from map() is > *also* in

Re: slicing functionality for strings / Python suitability forbioinformatics

2005-09-20 Thread Steven D'Aprano
if c not in self.__class__.alphabet: raise ValueError('Illegal character "%s".' % c) self.value = array.array('c', value) def __repr__(self): return self.value.tostring() and so on. Obviously you will need more work than this, and it may be possible to subclass array directly. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Question About Logic In Python

2005-09-20 Thread Steven D'Aprano
On Mon, 19 Sep 2005 22:31:05 +, Bengt Richter wrote: > On Mon, 19 Sep 2005 23:46:05 +1000, Steven D'Aprano <[EMAIL PROTECTED]> wrote: >>Are there actually any usage cases for *needing* a Boolean value? Any >>object can be used for truth testing, eg: [snip] >

Re: Question About Logic In Python

2005-09-20 Thread Steven D'Aprano
On Tue, 20 Sep 2005 03:03:15 +, Ron Adam wrote: > Steven D'Aprano wrote: >> Are there actually any usage cases for *needing* a Boolean value? Any >> object can be used for truth testing, eg: [snip] > Of course if any of the default False or True conditions are > i

Re: print there!

2005-09-20 Thread Steven D'Aprano
dwin\\bl.csv', > for i,row in enumerate(reader): > # inserts or updates the database > print "\r" + filename, i, > print That may not be enough. You may need to flush the print buffer using sys.stout.flush(). -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Finding where to store application data portably

2005-09-21 Thread Steven D'Aprano
with ls, but in these days of GUI file managers, it is ridiculous that there are more than 100 dot files and directories in my home directory. Can I ask developers to break with the obsolete and annoying habit of creating user-specific config files as ~/.app-name and use ~/settings/app-name

Re: slicing functionality for strings / Python suitability forbioinformatics

2005-09-21 Thread Steven D'Aprano
On Wed, 21 Sep 2005 11:37:38 +0100, Tom Anderson wrote: > There's a special hell for people who override builtins. [slaps head] Of course there is, and I will burn in it for ever... -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Writing a parser the right way?

2005-09-21 Thread Steven Bethard
Christopher Subich wrote: > beza1e1 wrote: > >> Well, a declarative sentence is essentially subject-predicate-object, >> while a question is predicate-subject-object. This is important in >> further processing. So perhaps i should code this order into the >> classes? I need to think a little bit m

Re: C#3.0 and lambdas

2005-09-21 Thread Steven D'Aprano
plicit tuple unpacking in the body of a function is faster than tuple unpacking (implicit or explicit) in the header of a function. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: C#3.0 and lambdas

2005-09-21 Thread Steven Bethard
Steven D'Aprano wrote: > I would love to see your test code and profiling results that demonstrate > that explicit tuple unpacking in the body of a function is faster than > tuple unpacking (implicit or explicit) in the header of a function. Should be pretty close. I believe th

Re: Question About Logic In Python

2005-09-21 Thread Steven D'Aprano
On Wed, 21 Sep 2005 18:53:34 +, Ron Adam wrote: > Steven D'Aprano wrote: > >>>So.. >>> >>>bool(a and b) * value >>> >>>Would return value or zero, which is usually what I want when I do this >>>type of expression. >

Re: Finding where to store application data portably

2005-09-21 Thread Steven D'Aprano
eginning with '.'? I don't want to hide them. I just don't want them in my face when I open my home directory. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Finding where to store application data portably

2005-09-22 Thread Steven D'Aprano
x27;t), then it is a serious security risk. You, the user might not be able to hide the files, but you can bet some virus will. Eg if you drop an executable file in the Windows XP font directory, it will not show up in the file explorer. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list

Re: Writing a parser the right way?

2005-09-22 Thread Steven Bethard
beza1e1 wrote: > Verbs are the tricky part i think. There is no way to recognice them. > So i will have to get a database ... work to do. ;) Try the Brill tagger[1] or MXPOST[2]. STeVe [1] http://www.cs.jhu.edu/~brill/code.html [2] ftp://ftp.cis.upenn.edu/pub/adwait/jmx/jmx.tar.gz -- http://mai

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Nick Coghlan wrote: By assigning to __dict__ directly, you can use the attribute view either as it's own dictionary (by not supplying one, or supplying a new one), or as a convenient way to programmatically modify an existing one. For example, you could use it to easily bind globals without need

Re: Multiple constructors

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: If you want to do this all the time, you could even build appropriate infrastructure for this task -- a little custom descriptor and metaclass, and/or decorators. Such infrastructure building is in fact fun and instructive -- as long as you don't fall into the trap of *using* s

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I wrote this little piece of code to get a list of relative paths of all files in or below the current directory (*NIX): walkList = [(x[0], x[2]) for x in os.walk(".")] filenames = [] for dir, files in walkList: filenames.extend(["/".join([dir, f]) for

Re: remove duplicates from list *preserving order*

2005-02-06 Thread Steven Bethard
Francis Girard wrote: I think your last solution is not good unless your "list" is sorted (in which case the solution is trivial) since you certainly do have to see all the elements in the list before deciding that a given element is not a duplicate. You have to exhaust the iteratable before yie

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: I think this ``view'' or however you call it should be a classmethod too, for the same reason -- let someone handily subclass Bunch and still get this creational pattern w/o extra work. Maybe a good factoring could be something like: class Bunch(object): def __init__(self,

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
On 6 Feb 2005 11:28:37 -0800, <[EMAIL PROTECTED]> wrote: > > walkList = [(x[0], x[2]) for x in os.walk(".")] > filenames = [] > for dir, files in walkList: > filenames.extend(["/".join([dir, f]) for f in files]) Caleb Hattingh top-posted: I would be interested to see an example

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
Caleb Hattingh wrote: filenames = [os.path.join(dirpath, filename) # This is cool for dirpath, _, filenames in os.walk('.') # This is getting tricky, whats the '_' for? Nothing to do with the list comprehension really. '_' is a commonly used variable name

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I don't know what the right solution is here... I wonder if I should write a classmethod-style descriptor that disallows the calling of a function from an instance? Or maybe I should just document that the classmethods

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: at the OP's original code, the line: [(x[0], x[2]) for x in os.walk(".")] is the equivalent of: [dirpath, filenames for dirpath, dirnames, filenames in os.walk('.')] Just a nit: you need parenth

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Michael Spencer wrote: ISTM that 'bunch' or 'namespace' is in effect the complement of vars i.e., while vars(object) => object.__dict__, namespace(somedict) gives an object whose __dict__ is somedict. Yeah, I kinda liked this application too, and I think the symmetry would be nice. Looked at th

Re: remove duplicates from list *preserving order*

2005-02-06 Thread Steven Bethard
John Machin wrote: So, just to remove ambiguity, WHICH one of the bunch should be retained? Short answer: "the first seen" is what the proverbial "man in the street" would expect For my purposes, it doesn't matter which instance is retained and which are removed, so yes, retaining the first one is

Re: overwriting method in baseclass

2005-02-06 Thread Steven Bethard
Harald Massa wrote: Hello! I am using a library (= code of so else) within Python. Somewhere in this library there is: class foo: def baa(self, parameters): print "something" self.baazanan(some other parameters) class mirbo(foo): def baazanan(self, lalala):

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Nick Coghlan wrote: Finally, I've just used normal names for the functions. I think the issue of function shadowing is best handled by recommending that all of the functions be called using the class explicitly - this works just as well for instance methods as it does for class or static methods

Re: Confused with methods

2005-02-07 Thread Steven Bethard
jfj wrote: I think the problem is that you know python so well that you are used to the way things are and everything seems natural the way it is. For a newbie, the behaviour I mentioned seems indeed a bit inconsistent. "Inconsistent" not as in mathematics but as in "wow! I'd thought this should wo

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: I'm very sorry that there is no good use case for the "reduce" function in Python, like Peter Otten pretends. That's an otherwise very useful tool for many use cases. At least on paper. Clarity aside[1], can you give an example of where reduce is as efficient as the eqival

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Michael Spencer wrote: Nick Coghlan wrote: Steven Bethard wrote: It was because these seem like two separate cases that I wanted two different functions for them (__init__ and, say, dictview)... I see this, but I think it weakens the case for a single implementation, given that each

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: Is there someone on this list using this tool and happy with it ? Or is my mind too much targeted on FP paradigm and most of you really think that all the functions that apply another function to each and every elements of a list are bad (like "reduce", "map", "filter") ? I

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
John Lenton wrote: For example, the fastest way to get the factorial of a (small enough) number in pure python is factorial = lambda n: reduce(operator.mul, range(1, n+1)) Gah! I'll never understand why people use lambda, which is intended to create _anonymous_ functions, to create named functi

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: Le lundi 7 Février 2005 20:30, Steven Bethard a écrit : especially since I avoid lambda usage, and would have to write these as: Why avoid "lambda" usage ? You find them too difficult to read (I mean in general) ? Yup, basically a readability thing. I also tend to

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Carlos Ribeiro wrote: On Mon, 07 Feb 2005 11:50:53 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: Michael Spencer wrote: We could use __add__, instead for combining namespaces I don't think this is a good idea. For the same reasons that dicts don't have an __add__ (how should

Re: loops -> list/generator comprehensions

2005-02-07 Thread Steven Bethard
Caleb Hattingh wrote: Would filenames = [os.path.join(dirpath, filename) for dirpath, dirnames, filenames in os.walk('.') for filename in filenames] have been clearer for you? Then all you have to do is remember the order of the for-loop execution: Bizarr

Re: returning True, False or None

2005-02-07 Thread Steven Bethard
Matteo Dell'Amico wrote: Since a function that doesn't return is equivalent to one that returns None, you can write it as: >>> def doit(lst): ... s = set(lst) - set([None]) ... if s: return max(s) that looks to me as the most elegant so far, but this is just because it's mine :-) Cool.

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: I see. I personnaly use them frequently to bind an argument of a function with some fixed value. Modifying one of the example in http://mail.python.org/pipermail/python-list/2004-December/257990.html I frequently have something like : SimpleXMLRPCServer.py: server.register

Re: def __init__ question in a class definition rephrased

2005-02-07 Thread Steven Bethard
Jeffrey Borkent wrote: what is the significance ( if any ) of the __ in these self.xx assignments. Variables with preceding __ are a vague attempt to avoid some types of name collisions in inheritance hierarchies. Any name that starts with a __ will be mangled by prefixing it with _: py> cl

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Michael Spencer wrote: I see no problem in repeating the methods, or inheriting the implementation. However, if namespace and bunch are actually different concepts (one with reference semantics, the other with copy), then __repr__ at least would need to be specialized, to highlight the differen

Re: Name of type of object

2005-02-09 Thread Steven Bethard
Randall Smith wrote: Jive Dadson wrote: The traceback routine prints out stuff like, NameError: global name 'foo' is not defined NameError is a standard exception type. What if I want to print out something like that? I've determined that "global name 'foo' is not defined" comes from the __str

Re: convert list of tuples into several lists

2005-02-09 Thread Steven Bethard
Diez B. Roggisch wrote: zip(*[(1,4),(2,5),(3,6)]) While this is also the approach I would use, it is worth noting that Guido thinks of this as an abuse of the argument passing machinery: http://mail.python.org/pipermail/python-dev/2003-July/037346.html Steve -- http://mail.python.org/mailman/list

Re: convert list of tuples into several lists

2005-02-09 Thread Steven Bethard
Peter Hansen wrote: Steven Bethard wrote: Diez B. Roggisch wrote: zip(*[(1,4),(2,5),(3,6)]) While this is also the approach I would use, it is worth noting that Guido thinks of this as an abuse of the argument passing machinery: http://mail.python.org/pipermail/python-dev/2003-July/037346.html

Re: empty classes as c structs?

2005-02-09 Thread Steven Bethard
Alex Martelli wrote: Nick Coghlan <[EMAIL PROTECTED]> wrote: We could use __add__, instead for combining namespaces Update already let's us combine namespaces. To create a new object that merges two namespaces do: namespace.update(namespace(ns_1), ns_2) One thing I'd like to see in namespaces

Re: empty classes as c structs?

2005-02-09 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I didn't know what to do for __setattr__... Was that what you meant by "The best semantics for _bindings_ as opposed to lookups isn't clear though"? Yep. __delattr__ ain't too obvious to me either, th

Re: convert list of tuples into several lists

2005-02-10 Thread Steven Bethard
Cappy2112 wrote: What does the leading * do? Tells Python to use the following iterable as the (remainder of the) argument list: py> def f(x, y): ... print x, y ... py> f([1, 2]) Traceback (most recent call last): File "", line 1, in ? TypeError: f() takes exactly 2 arguments (1 given) py>

Re: empty classes as c structs?

2005-02-10 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I like the idea of chain, though, so I'll probably add the class with just __init__ and __getattribute__ to the current implementation. I'm willing to be persuaded, of course, but for the moment, since I can see

namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-10 Thread Steven Bethard
d the current implementation of the module at the end of the PEP.) -- PEP: XXX Title: Attribute-Value Mapping Data Type Version: Last-Modified: Author: Steven Bethard <[EMAIL PROTECTED]> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 10-Feb-2005 P

Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-10 Thread Steven Bethard
Jeremy Bowers wrote: On Thu, 10 Feb 2005 11:56:45 -0700, Steven Bethard wrote: In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that i

Re: convert list of tuples into several lists

2005-02-11 Thread Steven Bethard
Pierre Quentel wrote: Could someone explain why this doesn't work : Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(*args,**kw): ... print args, kw ... >>> f(*[1,2]) (1, 2) {} >>>

check if object is number

2005-02-11 Thread Steven Bethard
Is there a good way to determine if an object is a numeric type? Generally, I avoid type-checks in favor of try/except blocks, but I'm not sure what to do in this case: def f(i): ... if x < i: ... The problem is, no error will be thrown if 'i' is, say, a string: p

Re: check if object is number

2005-02-11 Thread Steven Bethard
Bill Mill wrote: On Fri, 11 Feb 2005 12:11:44 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: Is there a good way to determine if an object is a numeric type? How about: if type(variable) == type(1): print "is an integer" else: print "please input an integer"

Re: check if object is number

2005-02-11 Thread Steven Bethard
Dan Bishop wrote: Steven Bethard wrote: Is there a good way to determine if an object is a numeric type? How about this? ... def is_number(x): ...try: ... x + 1 ... return True ...except TypeError: ... return False Great, thanks! That's the kind of thing I was lo

Re: check if object is number

2005-02-11 Thread Steven Bethard
George Sakkis wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a good way to determine if an object is a numeric type? In your example, what does your application consider to be numeric? Well, here's the basic code: def f(max=None):

Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-12 Thread Steven Bethard
Nick Coghlan wrote: There *is* a problem with using __getattr__ though - any attribute in the chained namespaces that is shadowed by a class attribute (like 'update') will be picked up from the class, not from the chained namespaces. So we do need to use __getattribute__ to change that lookup o

Re: check if object is number

2005-02-12 Thread Steven Bethard
George Sakkis wrote: For the record, here's the arbitrary and undocumented (?) order among some main builtin types: None < 0 == 0.0 < {} < [] < "" < () If you're curious, you can check the source code. Look for default_3way_compare in object.c. Basically the rundown for dissimilar types is: *

Re: exception handling for a function returning several values

2005-02-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: If a function that normally returns N values raises an exception, what should it return? Depends on what you want to do with the result of the function. N values of None seems reasonable to me, so I would write code such as def foo(x): try: # code setting y and z

Re: pre-check for string-to-number conversion

2005-02-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I am reading an ASCII data file and converting some of the strings to integers or floats. However, some of the data is corrupted and the conversion doesn't work. I know that I can us exceptions, but they don't seem like the cleanest and simplest solution to me. You should r

Re: check if object is number

2005-02-12 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: Is there a good way to determine if an object is a numeric type? assert operator.isNumberType(i) Interesting, thanks! If I read the source right, PyNumber_Check (which operator.isNumberType is an alias for) basically just returns True if the object&#

Re: check if object is number

2005-02-12 Thread Steven Bethard
John Lenton wrote: On Fri, Feb 11, 2005 at 01:17:55PM -0700, Steven Bethard wrote: George Sakkis wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a good way to determine if an object is a numeric type? In your example, what does

Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-12 Thread Steven Bethard
Nick Coghlan wrote: Steven Bethard wrote: >>> ns = Namespace(eggs=1) >>> Namespace.update(ns, [('spam', 2)], ham=3) >>> ns Namespace(eggs=1, ham=3, spam=2) Note that update should be used through the class, not through the instances, to avoid

Re: check if object is number

2005-02-12 Thread Steven Bethard
George Sakkis wrote: George Sakkis wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a good way to determine if an object is a numeric type? In your example, what does your application consider to be numeric? Well, here's the basic

Re: check if object is number

2005-02-12 Thread Steven Bethard
Peter Hansen wrote: Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. Or maybe not. (Pretty much all of them will call an arange a number... would the OP's fun

Re: check if object is number

2005-02-12 Thread Steven Bethard
Michael Spencer wrote: Steven Bethard wrote: Peter Hansen wrote: Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. How about explicitly calling an

Re: help please

2005-02-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: t2="" def Proc(text): # "text" is some random text or use OrigText for word in text: for letter in word: if letter in std.keys(): letter=std[letter] t2=t2+letter # the problem is referene to this elif lett

Re: help please

2005-02-12 Thread Steven Bethard
Erik Max Francis wrote: [EMAIL PROTECTED] wrote: UnboundLocalError: local variable 't2' referenced before assignment ... t2="" def Proc(text): # "text" is some random text or use OrigText ... The fix is to declare t2 global at the top of Proc: def Proc(text): global t2 .

Re: help please

2005-02-13 Thread Steven Bethard
gargonx wrote: This works much better, aside from the fact that it does'nt work for the std dictionary. the letters used from here stay the same. that dictionary looks like this: std = { "A":"Z", "Z":"A", "B":"Y", "Y":"B", "C":"X", "X":"C", "E":"V", "V":"E", "H":

Re: changing __call__ on demand

2005-02-13 Thread Steven Bethard
Stefan Behnel wrote: Is there a way to change __call__ after class creation? Check out this thread on the topic: http://mail.python.org/pipermail/python-list/2004-January/203142.html Basically, the answer is no -- at least not on a per-instance basis. You can try something like: py> class Test(ob

Re: help please

2005-02-13 Thread Steven Bethard
gargonx wrote: yes the items in std are always single to single, and ext single to double. basicly the ext are refernce to the std itmes. the second character in ext is a number depending on how far it is from the item in std. this is just a simple encoding program. If your keys are always single c

Re: builtin functions for and and or?

2005-02-13 Thread Steven Bethard
Roose wrote: I need this a lot: a one line way to do a n-ary and or 'or'. e.g., result = True for x in L: if not boolean_function(x): result = False or reduce(operator.__and__, [boolean_function(x) for x in L) Can you use itertools? py> def boolfn(x): ... print "boolfn: %r" % x ... re

Re: help please

2005-02-13 Thread Steven Bethard
gargonx wrote: Well that seems to work like a champion, but my prob then would be; how do i get the double character values of ext to turn back to the single character keys. The reversed (decode if you will). It's unclear what you want to do here. If you have say: ext = dict(aa='A', ab='B', bb='C'

Re: builtin functions for and and or?

2005-02-13 Thread Steven Bethard
Brian Beck wrote: Roose wrote: I need this a lot: a one line way to do a n-ary and or 'or'. Here's a one-liner for the n-ary and: bool(min(bool(x) for x in L)) py> bool(min(bool(x) for x in [1, 1, 1, 0])) False py> bool(min(bool(x) for x in [1, 1, 1, 1])) True py> bool(min(bool(x) for x in ['a', ''

<    43   44   45   46   47   48   49   50   51   52   >