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
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
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
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
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
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&
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
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
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&
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
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:
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 =
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
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
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-
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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)
[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
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
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
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__:
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()
>
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
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
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
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
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
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
[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,
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
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
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
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,
...
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
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
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
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
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
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)
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
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
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
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
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
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
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 !!!
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
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
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
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
[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
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
[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
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
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
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
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
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_
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
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
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>
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
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!"
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
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
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
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
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
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
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
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)
$
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
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
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
# ...
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
601 - 700 of 1538 matches
Mail list logo