Re: assymetry between a == b and a.__eq__(b) (WAS: pre-PEP genericobjects)

2004-12-01 Thread Steven Bethard
Terry Reedy wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message >>>def __eq__(self, other): """x.__eq__(y) <==> x == y""" return (isinstance(other, self.__class__) Since an instance of a subclass is an instance of a parent

app with support for multiple Python versions

2004-12-02 Thread Steven Bethard
I have a friend developing an app that has bindings for a variety of languages (e.g. Python, Perl, Tcl, Java, etc.). In order to provide the Python support, he uses tclpython (http://jfontain.free.fr/tclpython.htm). If he builds tclpython with, say, Python 2.3, I have to download a source version

Re: efficient intersection of lists with rounding

2004-12-02 Thread Steven Bethard
Gordon Williams wrote: I have to lists that I need to find the common numbers (2nd rounded to nearest integral) and I am wondering if there is a more efficient way of doing it. a= [(123,1.3),(123,2.4),(123,7.8),(123,10.2)] b= [(123, 0.9), (123, 1.9), (123, 8.0)] [ (i,round(j)) for i,j in a for l,m

Re: pre-PEP generic objects

2004-12-02 Thread Steven Bethard
Istvan Albert wrote: Steven Bethard wrote: I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be apprecia

Re: efficient intersection of lists with rounding

2004-12-02 Thread Steven Bethard
Michael Hoffman wrote: Steven Bethard wrote: Well, in Python 2.3, I believe sets are implemented in Python while they're implemented in C in Python 2.4. I think the Python 2.3 Sets implementation is likely to be quicker than whatever list-manipulation answer you come up with instead. But th

Re: assymetry between a == b and a.__eq__(b)

2004-12-03 Thread Steven Bethard
Mel Wilson wrote: In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: I believe what Peter Otten was pointing out is that calling __eq__ is not the same as using ==, presumably because the code for == checks the types of the two objects and returns False if they&

Re: pre-PEP generic objects

2004-12-03 Thread Steven Bethard
Istvan Albert wrote: On the other hand, it would be nice to have a module that implements various design patterns. The Bunch, the Borg, the Null, the Proxy all nicely documented tucked away in their separate module. That would feel a lot less like littering the standard name space with an class tha

Re: pre-PEP generic objects

2004-12-03 Thread Steven Bethard
Ian Bicking wrote: class bunch(object): def __init__(self, **kw): for name, value in kw.items(): # IMPORTANT! This is subclass friendly: updating __dict__ # is not! setattr(self, name, value) Good point about being subclass friendly... I wonder if t

Re: assymetry between a == b and a.__eq__(b)

2004-12-03 Thread Steven Bethard
Mel Wilson wrote: In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: I believe what Peter Otten was pointing out is that calling __eq__ is not the same as using ==, presumably because the code for == checks the types of the two objects and returns False if they&

Re: pre-PEP generic objects

2004-12-04 Thread Steven Bethard
Istvan Albert wrote: but what are you saying? that a man cannot exaggerate and fudge the facts in order to embellish his argument? :-) Heh heh. Yeah, something like that. ;) Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: Refactoring a generator function

2004-12-04 Thread Steven Bethard
Kent Johnson wrote: Here is a simple function that scans through an input file and groups the lines of the file into sections. Sections start with 'Name:' and end with a blank line. The function yields sections as they are found. def makeSections(f): currSection = [] for line in f:

Re: [Python-Help] (fwd)

2004-12-05 Thread Steven Bethard
Craig Ringer wrote: As you can see, it's much easier to work with data in lists. Some of the other methods, like list.sort() and list "slices" will also be useful to you, but I'll let you figure out the details ;-) . Something else that might be useful to you if you're using Python 2.4: >>> lst =

Re: [Python-Help] (fwd)

2004-12-05 Thread Steven Bethard
Craig Ringer wrote: It looks to me like you'd be better off reading each input number into a list. You may also find it useful to write a generator function to read your values in: >>> def read_numbers(): ... while True: ... number = int(raw_input('Enter a number: ')) ... if n

Re: convert string to raw string?

2004-12-06 Thread Steven Bethard
Duncan Booth wrote: If you are getting input from the user, then unless you are doing some processing on it to interpret escape sequences the chances are you already have what you need to use as a regular expression. If you *are* interpreting escape sequences then the answer is you need to not d

Re: Mean, median, and mode

2004-12-06 Thread Steven Bethard
Paul Rubin wrote: median = x.sorted()[len(x)//2] In Python 2.4: >>> [10, 8, 6, 4, 2, 1].sorted() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'sorted' Perhaps you meant "sorted(x)"? Steve -- http://mail.python.org/mailman/listinfo/python-

Re: Help with super()

2004-12-06 Thread Steven Bethard
Christopher J. Bottaro wrote: Why don't this code work? import PRI class Poscdnld_PYIO(PRI.BasicBatch): def __init__(self, *argv): super(Poscdnld_PYIO, self).__init__(*argv) x = Poscdnld_PYIO() I get this exception: File "poscdnld_pyio.py", line 52, in __init__ super(Poscdnld_PYIO

Re: Time for : comp.lang.python.newbies ??

2004-12-07 Thread Steven Bethard
James Stroud wrote: As far as lists go, this is my favorite, and I've subscribed to lists in a variety of fields. I'm afraid that scaring off newbies would remove some of the charm of this list. Amen. =) And anyway, with a good newsreader, you can just ignore any threads that are too "newbie" fo

Re: Find index of item in list

2004-12-07 Thread Steven Bethard
wes weston wrote: Sean Berry wrote: myList = ['cat', 'dog', 'mouse' ... 'bear'] what is the easiest way to find out what index 'dog' is at? >>> myList = ['cat', 'dog', 'mouse','bear'] >>> myList.index('dog') 1 >>> Yup, list.index is almost certainly what you want, though it's worth mentioning t

Re: Import a module without executing it?

2004-12-07 Thread Steven Bethard
Jay O'Connor wrote: -- def test(var): print var #main test(3) -- I want to be able to import this module so I can see "ah ha, this module defines a function called 'test'", but I don't want the code at the bottom executed during the import. If you have

Re: Sorting in huge files

2004-12-07 Thread Steven Bethard
Paul wrote: I expect a few repeats for most of the keys, and that s actually part of what I want to figure out in the end. (Said loosely, I want to group all the data entries having "similar" keys. For this I need to sort the keys first (data entries having _same_ key), and then figure out which ke

Re: How do I do this? (eval() on the left hand side)

2004-12-07 Thread Steven Bethard
It's me wrote: How do I do something like this: I know that a = 3 y = "a" print eval(y) would give me a print out of 3 - but how do I do something to the effect of: eval(y) = 4# hopefully the value of a gets changed to 4 Generally, if you find yourself doing this, you may want t

Re: Sorting in huge files

2004-12-07 Thread Steven Bethard
Paul wrote: Is this reasonnable to do on 10^8 elements with repeats in the keys? I guess I should just try and see for myself. Yeah, that's usually the right solution. I didn't comment on space/speed issues because they're so data dependent in a situation like this, and without actually looking

Re: How do I do this? (eval() on the left hand side)

2004-12-07 Thread Steven Bethard
It's me wrote: For simplicity sake, let's say I need to do something like this (for whatever reason): If I had a situation like this, I'd probably store my 'variables' as keys in a dict, e.g.: >>> bindings = {} >>> for i in range(3): ... name = raw_input('Name: ') ... value = int(raw_i

Re: Help with generators outside of loops.

2004-12-07 Thread Steven Bethard
Robert Brewer wrote: Christopher J. Bottaro wrote: I have a generator that works like this: for row in obj.ExecSQLQuery(sql, args): # process the row Now there are some querys that run where I know the result will only be a single row. Is there anyway to get that single row from the genera

Re: 2D array

2004-12-07 Thread Steven Bethard
LutherRevisited wrote: I'm wanting to do something with a list that is basically a 2 dimensional array. I'm not so good with lists so can someone give me an example of how I might implement this in Python? thanks. If you're planning to do anything serious with a 2D array, you should probably loo

guarding for StopIteration (WAS: Help with generators outside of loops.)

2004-12-08 Thread Steven Bethard
David Eppstein wrote: I've made it a policy in my own code to always surround explicit calls to next() with try ... except StopIteration ... guards. Otherwise if you don't guard the call and you get an unexpected exception from the next(), within a call chain that includes a for-loop over anoth

Re: guarding for StopIteration (WAS: Help with generators outside of loops.)

2004-12-08 Thread Steven Bethard
Steven Bethard wrote: Just to clarify here, the only time code raising a StopIteration will cause a for-loop to exit silently is if the StopIteration is raised in an __iter__ method, e.g.: That was a little imprecise. What I should have said is "the only time code raising a StopIteration

Re: creating generators from function

2004-12-08 Thread Steven Bethard
Simon Wittber wrote: I use a coroutine/generator framework for simulating concurrent processes. To do this, I write all my functions using the general form: while True: do stuff yield None To make these generator functions compatible with a standard thread interface, I attempted to write a

updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-08 Thread Steven Bethard
Peter Hansen wrote: Nick Coghlan wrote: Generally, altering the contents of the dicts returned by locals() and globals() is unreliable at best. Nick, could you please comment on why you say this about globals()? I've never heard of any possibility of "unreliability" in updating globals() and, as

Re: Help with generators outside of loops.

2004-12-08 Thread Steven Bethard
Christopher J. Bottaro wrote: Wow, good advice. One question, how is the generator class implemented so that if assigned to a tuple/list, it knows what to do? Is it possible to overload the assignment operator kinda like in C++? Tuple unpacking works with generators because generators implement t

Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Adam DePrince wrote: def flatten( i ): try: i = i.__iter__() while 1: j = flatten( i.next() ) try: while 1: yield j.next() except StopIteration: pass except AttributeError: yield

Re: 2D array

2004-12-08 Thread Steven Bethard
Adam DePrince wrote: If your data is sparse you might want to consider using a dictionary where the key is a tuple representing the coordinates. a = {} a[(0,0)] = 0 a[(0,1)] = 1 [snip] print a.get( (5,0), None ) Good point. Note that you don't need the parentheses in the assignments or item acces

Re: updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-08 Thread Steven Bethard
Caleb Hattingh wrote: Steve, I don't think I understand. Here is what I just tried: '>>> def f(): x = 3 d = locals() print x print d['x'] d['x'] = 5 print x '>>> f() 3 3 3 '>>> In your example, x had not yet been initialised, maybe. What I am seeing is that "x" doe

Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Peter Otten wrote: I noted that strings don't feature an __iter__ attribute. Therefore obj.__iter__() is not equivalent to iter(obj) for strings. Do you (plural) know whether this is a CPython implementation accident or can be relied upon? Nick Craig-Wood wrote: > With a little more investigation I

Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Adam DePrince wrote: On Wed, 2004-12-08 at 15:02, Steven Bethard wrote: Note that I special-case strings because, while strings support the iterator protocol, in this case we want to consider them 'atomic'. By catching the TypeError instead of an AttributeError, I can support

Re: 2D array

2004-12-08 Thread Steven Bethard
Adam DePrince wrote: The use of None as the default parameter was on purpose; the lack of "magic" in python is often cited in religious wars between python and perl aficionados. Use of get(something, None) was on purpose, the level of familiarity with the language implied by the original question

Re: updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-08 Thread Steven Bethard
Jeff Shannon wrote: (Note also that functions which use exec cannot use the static namespace optimization, and thus tend to be *much* slower than normal functions (in addition to being a huge security problem). I don't know, however, whether locals() can update the local namespace in such un-op

exec'ing functions (WAS: updating locals() and globals())

2004-12-08 Thread Steven Bethard
Jeff Shannon wrote: Note also that functions which use exec cannot use the static namespace optimization, and thus tend to be *much* slower than normal functions In what circumstances will this be true? I couldn't verify it: > cat fib.py def fib1(n): a, b = 0, 1 while True: a, b

Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Terry Reedy wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Probably you want to catch a TypeError instead of an AttributeError; objects may support the iterator protocol without defining an __iter__ method: No, having an __iter__ method

Re: exec'ing functions (WAS: updating locals() and globals())

2004-12-08 Thread Steven Bethard
Jeff Shannon wrote: Steven Bethard wrote: Jeff Shannon wrote: Note also that functions which use exec cannot use the static namespace optimization, and thus tend to be *much* slower than normal functions In what circumstances will this be true? I couldn't verify it: [snip] I was referri

Re: Class Variable Inheritance

2004-12-08 Thread Steven Bethard
Brian "bojo" Jones wrote: It became clear to me that mastervar inside of class a is a static variable, and is associated with all instances of classes that extend class a. Yeah, that's basically what's happening. AFAICT, a variable declared at class level is shared with all subclasses (and is a

Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Terry Reedy wrote: This is a ways off, if ever, but I think the general advice for user code is to use the newer protocol. Yes, definitely. I hope no one misconstrued me to be suggesting that you should use the 'sequence protocol' for iterators (e.g. using __getitem__ and raising an IndexError)

Re: mapping function to vars

2004-12-09 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I need to map a function to several variables. I'm trying to use map and lambda to do this. Here's my attempt... #!/usr/bin/env python from random import * [fee, fye, foe, fum] = map(lambda n: random(), range(4)) print fee print fye print foe print fum ...I'm essentially

Re: Calling a C program from a Python Script

2004-12-09 Thread Steven Bethard
It's me wrote: I would expect C to run circles around the same operation under Python. You should probably only expect C to run circles around the same operations when those operations implemented entirely in Python. In the specific (trivial) example given, I wouldn't expect Python to be much s

Re: Possible to insert variables into regular expressions?

2004-12-09 Thread Steven Bethard
Chris Lasher wrote: I would like to create a set of very similar regular expression. In my initial thought, I'd hoped to create a regular expression with a variable inside of it that I could simply pass a string into by defining this variable elsewhere in my module/function/class where I compile th

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Fernando Perez wrote: I was wondering if someone can help me understand why __getslice__ has been deprecated, yet it remains necessary to implement it for simple slices (i:j), while __getitem__ gets called for extended slices (i:j:k). I don't think this is true -- everything goes to __getitem__:

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Fernando Perez wrote: classes which implement slicing must now do runtime type-checking inside __getitem__. Just in case you thought that they wouldn't have to do runtime type-checking otherwise: >>> class C(object): ... def __getitem__(self, x): ... print type(x), x ... >>> c = C() >

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Fernando Perez wrote: Steven Bethard wrote: Fernando Perez wrote: I was wondering if someone can help me understand why __getslice__ has been deprecated, yet it remains necessary to implement it for simple slices (i:j), while __getitem__ gets called for extended slices (i:j:k). I don't think

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Carl Banks wrote: As for why list objects still use getslice--they probably shouldn't. I'd file a bug report. I'm not convinced this is actually a bug; it works just like the docs promise: http://docs.python.org/ref/sequence-methods.htm

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Carl Banks wrote: Steven Bethard wrote: Unfortunately, I don't think __getslice__ can be removed from list (and str and tuple) because of backwards compatibility constraints... Wouldn't it work to have __getslice__ call __getitem__? And, since that would be too much of a performance hi

Re: threading problem

2004-12-09 Thread Steven Bethard
Egor Bolonev wrote: hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' [snip] threading.Thread(target = run, args = (os.path.join('c:\\', path))).start() I believe the args argument to threading.Thread is supposed to b

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Fernando Perez wrote: I guess that conceptually it just felt natural to me to keep separate methods for dealing with a slice (get many elements out) and other types of indexing, which I tend to think of as 'scalar' indexing. Yeah, I can see that a bit. Ignoring dicts for the moment (and concerning

Re: Rationale behind the deprecation of __getslice__?

2004-12-09 Thread Steven Bethard
Fernando Perez wrote: Anyway, thanks for the discussion, it clarified a few points. Likewise. I hadn't really delved much into the __getslice__ details until you found that quirk. Always good to have a motivator! Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: Find Items & Indices In A List...

2004-12-10 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Hello NG, I was wondering if there is a faster/nicer method (than a for loop) that will allow me to find the elements (AND their indices) in a list that verify a certain condition. For example, assuming that I have a list like: mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1,

Re: style query: function attributes for return codes?

2004-12-10 Thread Steven Bethard
george young wrote: This is obviously just evil, since a misspelling in the string return is treacherous. I'm considering function attributes: def get_connection(): if tcp_conn(): if server_allows_conn(): return get_connection.GOOD else: return get_conne

Re: style query: function attributes for return codes?

2004-12-10 Thread Steven Bethard
george young wrote: [python 2.3.3, x86 linux] I recently found myself writing something like: def get_connection(): if tcp_conn(): if server_allows_conn(): return 'good_conn' else: return 'bad_auth' else: return 'no_server' cn = get_connection

Re: style query: function attributes for return codes?

2004-12-10 Thread Steven Bethard
Robert Kern wrote: Steven Bethard wrote: Sorry, I also meant to add that the other obvious way of dealing with this kind of thing is to make the results keyword parameters: def get_connection(GOOD=1, BAD_AUTH=2, NO_SERVER=3): if tcp_conn(): if server_allows_conn(): return

Re: Possible to insert variables into regular expressions?

2004-12-10 Thread Steven Bethard
Terry Hancock wrote: And hey, you could probably use a regex to modify a regex, if you were really twisted. ;-) Sorry. I really shouldn't have said that. Somebody's going to do it now. :-P Sure, but only 'cause you asked so nicely. =) >>> import re >>> def internationalize(expr, ...

capwords (WAS: [Newby] question about modules)

2004-12-10 Thread Steven Bethard
Jon wrote: As far as I can tell from the online docs, "capwords" should be defined in the built-in "regex" module. Why is it telling me that capwords is not defined? Hmm... are you looking instead for "capwords" from the string module? >>> s = """\ ... Well, he's... ... he's, ah... ... probably pi

Re: Zip with a list comprehension

2004-12-10 Thread Steven Bethard
Matt Gerrans wrote: This is probably so easy that I'll be embarrassed by the answer. While enhancing and refactoring some old code, I was just changing some map()s to list comprehensions, but I couldn't see any easy way to change a zip() to a list comprehension.Should I just let those slee

Re: newbie questions

2004-12-11 Thread Steven Bethard
houbahop wrote: Thank you everyone, but I still not understand why such a comon feature like passing parameters byref that is present in most serious programming languages is not possible in a clean way,here in python. I understand from this statement that Java is not a serious programming langua

Re: newbie questions

2004-12-11 Thread Steven Bethard
houbahop wrote: Passing a pointer by value appears to me as passing a var by reference. Well, at least in the PL literature, there's a subtle difference. If Python supported pass-by-reference, you could do something like: >>> def clear(byref lst): ... lst = [] ... >>> x = [pow(x, 11, 17) for

Re: New versions breaking extensions, etc.

2004-12-11 Thread Steven Bethard
It's me wrote: My answer is simple: If there are more then 24 hours to a day, I definitely would... Can we get a patch in for this? >>> datetime.timedelta(hours=24) + datetime.timedelta(hours=1) datetime.timedelta(1) would be much preferable to the current: >>> datetime.timedelta(hours=24) + dateti

Re: newbie questions

2004-12-11 Thread Steven Bethard
houbahop wrote: Hello again everyone , var2[:]=[] has solved my problem, and I don't understand why it is programming by side effect. I don't think it's bad, look at this, it's what I've done : def Clear(lvar) lvar[:]=[] def main (starting class) var1=[] var1.append('a') Clear(var1)

Re: newbie questions

2004-12-12 Thread Steven Bethard
Fredrik Lundh wrote: John Machin wrote: Of course, in this simple case, I wouldn't be likely to write the clear function since the inline code is simpler and has less overhead: def main() var1 = [] var1.append('a') var1[:] = [] Even less overhead: del var1[:] even less overhead: v

Re: for loop

2004-12-12 Thread Steven Bethard
houbahop wrote: for i=morethanzero to n for i in range(morethanzero, n): ... for i= 5 to len(var) for i in range(5, len(var)): ... although range(len(var)) is usually not what you want, because you can just do: for item in itertools.islice(var, 5, None): ... or if you really do need t

Re: for loop

2004-12-12 Thread Steven Bethard
Diez B. Roggisch wrote: for i in range(5, len(var)): ... Better use xrange - it doesn't create an actual list, but instead an iterator enumerating the elements. That way more memory and cpu efficient. I could've sworn I read somewhere in the past that xrange was supposed to be slower than rang

Re: Python mascot proposal

2004-12-12 Thread Steven Bethard
Brian Beck wrote: http://exogen.cwru.edu/python2.png Oooh, I like this one. Very cool! Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: Cool object trick

2004-12-12 Thread Steven Bethard
dataangel wrote: Normally I'd just use class Obj(object): pass, but the advantage to this method is you can create an Obj like this: Obj(id="desktop", last=0, color=self.getColor(DESKTOP_COLOR)) You can pass all the attributes you want the object to have this way. Nifty :) Yup, that's basically

Re: character encoding conversion

2004-12-13 Thread Steven Bethard
Christian Ergh wrote: flag = true for char in data: if 127 < ord(char) < 128: flag = false if flag: try: data = data.encode('latin-1') except: pass A little OT, but (assuming I got your indentation right[1]) this kind of loop is exactly what the else clause of a

Re: jython and concatenation of strings

2004-12-13 Thread Steven Bethard
Jan Gregor wrote: Hello I found that price of += operator on string is too high in jython. For example 5000 such operations took 90 seconds (i generated html copy of table with 1000 rows and 5 columns). Generation of row data into separate string and joining after lead to time 13 seconds !!!

Re: Suggestion for "syntax error": ++i, --i

2004-12-13 Thread Steven Bethard
Peter Maas wrote: target = 'a=' sign = '-' operand = '-2' exec(target+sign+operand) Hopefully not too many people write code like above when it isn't much harder to write this without exec: >>> target = 'a' >>> sign = '-' >>> operand = '-2' >>> sign_functions = {'+':operator.pos, '-':operator.neg

Re: Python mascot proposal

2004-12-13 Thread Steven Bethard
Lenard Lindstrom wrote: Steven Bethard <[EMAIL PROTECTED]> writes: Brian Beck wrote: http://exogen.cwru.edu/python2.png Oooh, I like this one. Very cool! Its visually stunning. But under Windows gears show up in the DLL and batch file icons. Is that a problem? The fact that they show up i

Re: how do I "peek" into the next line?

2004-12-13 Thread Steven Bethard
Skip Montanaro wrote: les> suppose I am reading lines from a file or stdin. I want to just les> "peek" in to the next line, and if it starts with a special les> character I want to break out of a for loop, other wise I want to les> do readline(). Create a wrapper around the file ob

Re: do you master list comprehensions?

2004-12-13 Thread Steven Bethard
Will Stuyvesant wrote: data = [['foo','bar','baz'],['my','your'],['holy','grail']] result = [] for d in data: ... for w in d: ...result.append(w) print result ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail'] Take advantage of the fact that you can have more than one 'for' in a list

Re: how do I "peek" into the next line?

2004-12-13 Thread Steven Bethard
[EMAIL PROTECTED] wrote: now suppose I have read the first line already. then I read the second line and notice that there is a ">" in front (my special character) then I want the put back the second line into the file or the stdin. Amended iterator class example using my peekable recipe: >>> class

Re: how do I "peek" into the next line?

2004-12-13 Thread Steven Bethard
I wrote: ... while True: ... next = self.iter.peek() ... if not next or next.rstrip('\n') == "|": ... break ... yield self.iter.next() ... Actually, the 'not next' test is not necessary since I'm using an iterator over the file (end of fi

Re: how do I "peek" into the next line?

2004-12-13 Thread Steven Bethard
[EMAIL PROTECTED] wrote: now suppose I have read the first line already. then I read the second line and notice that there is a ">" in front (my special character) then I want the put back the second line into the file or the stdin. Another possibility -- have each call to __iter__ produce the next

Re: A problem with list

2004-12-13 Thread Steven Bethard
Tim Henderson wrote: def tokenizer(str, chr=' '): #heres a useful tool just like StringTokenizer feature in Java if chr != '': chr = chr[0] else: chr = ' ' x = "" tokens = [""] z = 0 for x in str: if x != chr: tokens[z] = tokens[z] + x else: z

Re: while 1 vs while True

2004-12-14 Thread Steven Bethard
Steve Holden wrote: Interestingly the same error occurs even when attempting sideways access: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import __builtin__ >>> __builtin__.None = "Rhubarb

Re: do you master list comprehensions?

2004-12-14 Thread Steven Bethard
Timothy Babytch wrote: Will Stuyvesant wrote: data = [['foo','bar','baz'],['my','your'],['holy','grail']] sum(data, []) ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail'] The second parameter passed to sum is just to overrride default initial value "zero". It's worth keeping in mind that this so

Re: gather information from various files efficiently

2004-12-14 Thread Steven Bethard
Klaus Neuner wrote: The straightforward way to solve this problem is to create a dictionary. Like so: [...] a, b = get_information(line) if a in dict.keys(): dict[a].append(b) else: dict[a] = [b] So I timed the three suggestions with a few different datasets: > cat builddict.py def askpermi

Re: Regular Expression

2004-12-14 Thread Steven Bethard
Michael McGarry wrote: Also I am trying to parse the following string to extract the number after load average. " load average: 0.04, 0.02, 0.01" In Python 2.4: >>> uptime='12:12:05 up 21 days, 16:31, 10 users, load average: 0.01, 0.02, 0.04' >>> _, avg_str = uptime.rsplit(':', 1) >>> avg_

cmp of multiple attributes (WAS: Why are tuples immutable?)

2004-12-16 Thread Steven Bethard
Roy Smith wrote: class Property: def __init__ (self, block, lot, zoning="Unknown"): self.block = block self.lot = lot self.zoning = zoning def __hash__ (self): return (self.block + self.lot) def __cmp__ (self, other): # I wish there was a less ver

Re: (No subject)

2004-12-16 Thread Steven Bethard
Jeremy Jones wrote: Mark Devine wrote: I'm brand new to python and I was wondering if anybody knew of a easy [snip] You could use string.lower (make sure you "import string"): string.lower is deprecated in Python 2.4. Better to go with str.lower as Diez B. Roggisch suggested: commands = [c.lowe

Re: create lowercase strings in lists - was: (No subject)

2004-12-16 Thread Steven Bethard
Michael Spencer wrote: ... conv = "".join(char.lower() for char in text if char not in unwanted) Probably a good place to use str.replace, e.g. conv = text.lower() for char in unwanted: conv = conv.replace(char, '') Some timings to support my assertion: =) C:\Documents and Settings\Steve>

Re: Why are tuples immutable?

2004-12-17 Thread Steven Bethard
jfj wrote: Why can't we __setitem__ for tuples? It seems from your suggestions here that what you really want is a single sequence type, list, instead of two sequence types: tuple and list. Under your design, list would support hash, and it would be up to the programmer to make sure not to modi

Re: Cool object trick

2004-12-17 Thread Steven Bethard
Alex Stapleton wrote: you can't do var = "varA" obj = struct(varA = "Hello") print obj.var and expect it to say Hello to you. The Bunch object from the PEP can take parameters in the same way that dict() and dict.update() can, so this behavior can be supported like: >>> b = Bunch({"varA":"Hello!"

Re: create lowercase strings in lists - was: (No subject)

2004-12-17 Thread Steven Bethard
Mark Devine wrote: the trouble is it throws up the following error for set: $ ./test.py Traceback (most recent call last): File "./test.py", line 23, in ? reflist = [normalize(element) for element in list1] File "./test.py", line 20, in normalize return set(text.split()) NameError: glob

Re: Cool object trick

2004-12-17 Thread Steven Bethard
Alex Stapleton wrote: you are setting the variable name in your code (b.varA), not generating the variable name in a string (var = "varA") (dictionary key) at run-time and fetching it from the __dict__ like i was attempting to describe. Ahh. Well if you just want to get an attribute, I don't se

Re: Cool object trick

2004-12-17 Thread Steven Bethard
Robert Brewer wrote: Alex Stapleton wrote: you can't do var = "varA" obj = struct(varA = "Hello") print obj.var and expect it to say Hello to you. Did you mean "print obj.varA"? I believe he meant that he wanted the equivalent of: getattr(obj, var) Steve -- http://mail.python.org/mailman/listinfo/p

Re: ".>>>" is a good idea! (OT, was: Re: do you master list comprehensions?)

2004-12-17 Thread Steven Bethard
Kent Johnson wrote: You can copy and paste from a Windows command prompt. It's a bit bizarre, but - In the system menu for a command window, pick Properties - On the Options tab, turn on Quick Edit mode - Now you can copy and paste with right-click (!). If you have text selected, right-click will

deprecate UserList? (WAS: Why no list heritable type?)

2004-12-17 Thread Steven Bethard
Sion Arrowsmith wrote: In article <[EMAIL PROTECTED]>, Mike Meyer <[EMAIL PROTECTED]> wrote: And before Python 2.2 there was the UserList class in the standard library. Which is still there in 2.4. Shouldn't it be depreciated by this point? Apart from compatibility issues as mentioned in the User

Re: Troubleshooting: re.finditer() creates object even when no match found

2004-12-17 Thread Steven Bethard
Chris Lasher wrote: I know that if I place a finditer() object in an iterative for loop, the loop will not execute, but is there some way I can test to see if the object contains no matches in the first place? Basically, you want to peek into an interable. See my recipes: http://aspn.activestate.c

Re: A completely silly question

2004-12-17 Thread Steven Bethard
Amir Dekel wrote: What I need from the program is to wait for a single character input, something like while(getchar()) in C. All those Python modules don't make much sence to me... sys.stdin.read(1) but if you're having trouble reading the module documentation, maybe you could elaborate on what

Re: A completely silly question

2004-12-17 Thread Steven Bethard
Mike Meyer wrote: That doesn't do what he wants, because it doesn't return until you hit a newline. Are you sure that's not just an artifact of how your terminal buffers data for sys.stdin? $ cat temp.py import sys char = sys.stdin.read(1) while char: print char char = sys.stdin.read(1) $

Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Jason Zheng wrote: I'm wondering why python still has limited lambda support. What's stopping the developers of python to support more lisp-like lambda function? This comes up every few weeks on the list. If you haven't already, check the archives in Google for 'anonymous def' or 'anonymous fu

Re: Troubleshooting: re.finditer() creates object even when no match found

2004-12-17 Thread Steven Bethard
Chris Lasher wrote: Is there any way to request a feature like this from the RE module keepers, whomever they may be? The most direct way would be to go to Python at sourceforge[1] and make a feature request to add peek to itertools. (This is probably the most reasonable location for it.) Reque

Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: Even if you could settle the syntax issue, once you've decided that you really do need a true block in an anonymous function, you're not really saving much space by not declaring it: def f(*args): # body line 1 # body line 2 # ...

expression form of one-to-many dict?

2004-12-17 Thread Steven Bethard
So I end up writing code like this a fair bit: map = {} for key, value in sequence: map.setdefault(key, []).append(value) This code basically constructs a one-to-many mapping -- each value that a key occurs with is stored in the list for that key. This code's fine, and seems pretty simple, bu

<    2   3   4   5   6   7   8   9   10   11   >