Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Fredrik Lundh wrote: I'm not sure what "func" is supposed to be in your examples... Just an extra variable used to make sure that the lambda was being used in a context (i.e. in an expression) where a simple def wouldn't suffice. If the example is confusing, consider the dict example instead.

Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Michael DeHaan wrote: True enough, but suppose you want a hash of anonymous functions as opposed to just a lexical? I've seen at least one reasonable example of this kind of thing: http://mail.python.org/pipermail/python-list/2004-October/245432.html Though I haven't yet seen an example that actual

Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Jason Zheng wrote: The true beauty of lambda function is not the convenience of creating functions without naming them. Lambda constructs truly enables higher-order function. For example, I can create a function A that returns a function B that does something interesting according to the argume

Re: expression form of one-to-many dict?

2004-12-17 Thread Steven Bethard
Tim Peters wrote: The point here is that there's a simple sequence or GE that I can throw to the dict constructor that spits out a dict with my one-to- one mapping. It's a simple sequence because it's a simple task. It's even simpler than perhaps it "should be", since it arbitrarily decides that,

Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: I've seen at least one reasonable example of this kind of thing: http://mail.python.org/pipermail/python-list/2004-October/245432.html the code he's referring to doesn't seem to use that construct anymore, so it's not obvious what &q

Re: better lambda support in the future?

2004-12-17 Thread Steven Bethard
Jeff Shannon wrote: It occurs to me that, in a statically compiled language, function definitions all happen before the program starts, and thus that definition can't be affected by other variables (i.e. an outer function's parameters). I think you might be confusing static compilation in a lang

Re: expression form of one-to-many dict?

2004-12-17 Thread Steven Bethard
Larry Bates wrote: Suggestion: It is a bad idea to name any variable "map". When you do, you destroy your ability to call Python's map function. Same goes for "list", "str", or any other built-in function. If you haven't been bitten by this you will, I was. A good reminder for all the newbies out

Re: Why no list heritable type?

2004-12-17 Thread Steven Bethard
Mike Meyer wrote: Actually, UserList and UserDict are just wrappers around the builtin types. So the performance hit is one Python function call - pretty much neglible. But new code should still subclass the builtins. Interesting that they're not fully compatible with the builtins: >>> dict(dict=35

Re: expression form of one-to-many dict?

2004-12-17 Thread Steven Bethard
Fernando Perez wrote: outlist = map(foo,inlist) is still better in my book, and far more readable, than outlist = [foo(x) for x in inlist] The map form, in this case, parses instantly in my brain, while the listcomp certainly takes a few cycles. And note that I'm not talking about the typing conci

Re: Is this a good use for lambda

2004-12-17 Thread Steven Bethard
Harlin Seritt wrote: Charlie Taylor wrote: I find that I use lambda functions mainly for callbacks to things like integration or root finding routines as follows. flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd) root = findRoot(xBeg, xEnd, lambda x: y2+ lp*(x-x2) -wallF

singing the praises of unicode and codecs

2004-12-10 Thread Steven Bethard
I just wanted to thank Python for making encodings so easy! I recently discovered that one of the tools I use stores everything in UTF-8, and so I was getting some off-by-one errors because I was treating things as strings. I added def __unicode__(self): return str(self).decode('utf

Re: [Newby] question about modules

2004-12-10 Thread Steven Bethard
Jon wrote: The following four lines of code: import sys, os, re sentence = raw_input("Enter a sentence: ") capwords (sentence) print sentence gives me the following error: NameError: name 'capwords' is not defined As far as I can tell from the online docs, "capwords" should be defined in the buil

Re: Rationale behind the deprecation of __getslice__?

2004-12-10 Thread Steven Bethard
Nick Coghlan wrote: Steven Bethard wrote: Carl Banks wrote: Wouldn't it work to have __getslice__ call __getitem__? And, since that would be too much of a performance hit, have it check whether its type is list (or str or tuple), and only call __getitem__ if it is not (i.e., only for subcl

Re: Python mascot proposal

2004-12-12 Thread Steven Bethard
Jeremy Bowers wrote: On Sun, 12 Dec 2004 20:54:38 +, Dimitri Tcaciuc wrote: I haven't came up with the name for that guy yet, so I'm leaving that for public suggestions :). It is time Python gets an official face in the Net! *cough* Anyway, I would like to hear your thoughts and suggestions.

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

2004-12-13 Thread Steven Bethard
Petr Prikryl wrote: Summary: In my opinion, the C-like prefix increment and decrement operators (++i and --i) should be marked as "syntax error". This would give some weird assymetry: >>> i = 1 >>> ++i Traceback ( File "", line 1 ++i ^ SyntaxError: invalid syntax >>> --i Traceback ( Fil

Re: RegEx: find all occurances of a single character in a string

2004-12-14 Thread Steven Bethard
Franz Steinhaeusler wrote: given a string: st="abcdatraataza" ^ ^ ^ ^ (these should be found) I want to get the positions of all single 'a' characters. (Without another 'a' neighbour) You could also try negative lookahead/lookbehind assertions: >>> st="abcdatraataza" >>> for m in re.findi

Re: while 1 vs while True

2004-12-14 Thread Steven Bethard
Steve Holden wrote: # Pre 2.2.1 compat. try: True, False except NameError: True = 1==1; False = 1==0 I believe this should work for all versions up to 2.4, and would also work with a 2.5 that made True and False constants. But if anyone can prove me wrong it would be you ... :-) Seems like it mig

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

2004-12-16 Thread Steven Bethard
Kent Johnson wrote: You can do the same thing using a PYTHONSTARTUP file - see http://docs.python.org/tut/node4.html#SECTION00424 You can change the prompts with import sys sys.ps1 = ' >>> ' sys.ps2 = ' ... ' Very cool. I didn't know about this. Does anyone know how to make it

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

2004-12-18 Thread Steven Bethard
Nick Coghlan wrote: Nick Coghlan wrote: Chris Lasher wrote: Hello, I really like the finditer() method of the re module. I'm having difficulty at the moment, however, because finditer() still creates a callable-iterator oject, even when no match is found. This is undesirable in cases where I would

Re: expression form of one-to-many dict?

2004-12-18 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: The map form, in this case, parses instantly in my brain, while the listcomp certainly takes a few cycles. And note that I'm not talking about the typing conciseness, but about the effort for my brain. But maybe I'm just wired funny :) Well,

Re: dot products

2004-12-19 Thread Steven Bethard
Rahul wrote: I want to compute dot product of two vectors stored as lists a and b.a and b are of the same length. . >>> import numarray as na . >>> a, b = na.arange(5), na.arange(5, 10) . >>> na.dot(a, b) . 80 Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: Is this a good use for lambda

2004-12-19 Thread Steven Bethard
Walter S. Leipold wrote: I've used lambda from time to time, but only socially, and I can quit any time I want... +1 QOTW Steve -- http://mail.python.org/mailman/listinfo/python-list

late evaluation of function arguments (WAS: expression form of one-to-many dict?)

2004-12-19 Thread Steven Bethard
Mike Meyer wrote: Personally, I'd love a language feature that let you create a function that didn't evaluate arguments until they were actually used - lazy evaluation. That lets you write the C ?: operator as a function, for a start. You can fake it with generator expresions: . >>> class C(objec

Re: Is this a good use for lambda

2004-12-19 Thread Steven Bethard
Simo Melenius wrote: Now, if lambda was more than an expr, dumping "lambda" keyword would be a convenient idea -- unnecessary keywords can make the language less clear in some cases. One could do with Python's plain and simple "def", like this: filter (def (x): x*2, myseq) (Disclaimer: Without thin

atmosphere on c.l.py (WAS: How about "pure virtual methods"?)

2004-12-19 Thread Steven Bethard
Alex Martelli wrote: Definitely not the c.l.py I recalled [snip] I guess I'm not going to stay around all that long this time. That would be a sad loss for all of us out here who very much appreciate your very deep knowledge of Python and your willingness to share it. I do understand the feeling

Re: atmosphere on c.l.py (WAS: How about "pure virtual methods"?)

2004-12-19 Thread Steven Bethard
Doug Holton wrote: Fredrik Lundh wrote: well, since I'm not in the ego-stroking business, what if I promise never to reply to posts by you, robert, and alex? That's not fair to the rest of us though :) That's not even fair to the non-rest of us. =) As I noted, "his answers ... are often very ins

Re: Writev

2004-12-19 Thread Steven Bethard
Adam DePrince wrote: Many other programmers have faced a similar issue; cStringIO, ''.join([mydata]), map( file.write, [mydata]) are but some attempts at making this process more efficient by jamming the components to be written into a sequence. I'm obviously misunderstanding something because I ca

Re: Writev

2004-12-19 Thread Steven Bethard
Adam DePrince wrote: file.writelines( seq ) and map( file.write, seq ) are the same; the former is syntactic sugar for the later. Well, that's not exactly true. For one thing, map(file.write, seq) returns a list of Nones, while file.writelines returns only the single None that Python functions w

Re: atmosphere on c.l.py (WAS: How about "pure virtual methods"?)

2004-12-19 Thread Steven Bethard
Doug Holton wrote: He was only acknowledging the problem to those 3 people who complained about it. I was making the point that others do not like being trolled either. Ahh, gotcha. Read your comment with the right intonation this time. =) Steve -- http://mail.python.org/mailman/listinfo/python

Re: accessing module global vars by name

2004-12-19 Thread Steven Bethard
Martin Drautzburg wrote: IOW how can I write something like # xxx.py for varName in ("foo", "bar"): magic.varName = 1 I think you want to use the dict returned by globals(). Modifying this dict can add/remove names from the global scope.[1] >>> foo Traceback (most recent call last): Fi

Re: Writev

2004-12-20 Thread Steven Bethard
Adam DePrince wrote: [snip great explanation] I want to include it because POSIX has a single OS call that conceptually maps pretty closely to writelines. writev can be faster because you don't have to do memory copies to buffer data in one place for it -- the OS will do that, and can sometimes de

Re: Recursive structures

2004-12-20 Thread Steven Bethard
Scott David Daniels wrote: if mytype not in AVOIDITER: try: for item in obj: walks(item, seen) except TypeError: pass try: for key, value in obj.items(): walks(key, seen) # Key might be object w/ hash method

Re: Silly questions about True and False

2004-12-20 Thread Steven Bethard
drs wrote: I just upgraded my Python install, and for the first time have True and False rather than 1 and 0. I was playing around at the command line to test how they work (for instance, "if 9:" and "if True:" both lead to the conditional being executed, but True == 9 -> False, that this would be

Re: Operators as functions

2004-12-20 Thread Steven Bethard
Peter Hansen wrote: However, none of this is considered the best approach these days, with the advent of list comprehensions and generator expressions. Here's the old approach (shown above) and the shiny new modern Pythonic approach (requires Python 2.4): >>> theList = range(10) >>> import operat

Re: Is this a good use for lambda

2004-12-21 Thread Steven Bethard
Nick Coghlan wrote: def compose(list_of_functions): application_order = reversed(list_of_functions) def composed(x): for f in application_order: x = f(x) return x return composed reversed returns an iterator to the list in reverse order, not a copy of the list: >>> lst = range

Re: Keyword arguments - strange behaviour?

2004-12-21 Thread Steven Bethard
[EMAIL PROTECTED] wrote: However, is there a good reason why default parameters aren't evaluated as the function is called? (apart from efficiency and backwards compatibility)? So, one of my really common use cases that takes advantage of the fact that default parameters are evaluated at function

Re: Tuple Question

2004-12-21 Thread Steven Bethard
VanL wrote: Why is this? >>> class MyTuple(tuple): ... def __getitem__(self, name): ... return tuple.__getitem__(self, name) ... >>> data = (1,2,3,4,5) >>> t = MyTuple(data) >>> t[0] Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __getitem__ TypeErr

Re: Lazy argument evaluation (was Re: expression form of one-to-many dict?)

2004-12-21 Thread Steven Bethard
Nick Coghlan wrote: def lazy(x, *args, **kwds): """Executes x(*args, **kwds) when called""" if args or kwds: return lambda : x(*args, **kwds) else: return x # No arguments, so x must be callable by itself [snip] Huh. I think I like the idea of lazy() much better than I like the curre

Re: input record sepArator (equivalent of "$|" of perl)

2004-12-21 Thread Steven Bethard
John Machin wrote: Nick Coghlan wrote: [snip] delimeter. Hey, Terry, another varmint over here! No, no. He's talking about a deli-meter. It's the metric standard for measuring subs and sandwiches. ;) Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: regular expression: perl ==> python

2004-12-21 Thread Steven Bethard
[EMAIL PROTECTED] wrote: 1) In perl: $line = "The food is under the bar in the barn."; if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; } in python, I don't know how I can do this? I don't know Perl very well, but I believe this is more or less the equivalent: >>> import re >>> line = "The food

Re: Why are tuples immutable?

2004-12-22 Thread Steven Bethard
Antoon Pardon wrote: Well the only suggestion I would make now is that it would be nice to have a second dict type that would make a copy of a key and insert that copy in the dictionary. (At least) two options here, depending on what you really need. (1) Use current dicts. They will still give you

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-22 Thread Steven Bethard
Nick Coghlan wrote: The longer I consider it, the more this seems like a valid analogy. There is nothing preventing dictionaries from having a rehash() method. Consider: # Mutate some value in mylist mylist.sort() # Mutate some key in mydict mydict.rehash() Well, you can already get the equivalen

Re: cmp of multiple attributes

2004-12-22 Thread Steven Bethard
Alex Martelli wrote: Comparisons of tuples, lists, etc, are *lexicographical*: the first items are compared; iff they're equal, then the second items, and so forth. IOW, exactly what you want in this case. Just to check my understanding, this means that: cmp(a0, b0) or cmp(a1, b1) or ... or cm

Re: list IndexError

2004-12-22 Thread Steven Bethard
Ishwor wrote: i am trying to remove an item 'e' from the list l I thought it might be helpful to code some of the alternatives you've been given and look at the timings to put things into perspective. The code: remove.py def remove_lc(x, lst): lst[:

Re: Lambda going out of fashion

2004-12-22 Thread Steven Bethard
Stephen Thorne wrote: { 'one': lambda x:x.blat(), 'two': lambda x:x.blah(), }.get(someValue, lambda x:0)(someOtherValue) The alternatives to this, reletively simple pattern, which is a rough parallel to the 'switch' statement in C, involve creating named functions, and remove the code from the co

Re: Lambda going out of fashion

2004-12-22 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Well, you can say apply() is 'deprecated' now, (which is another functional thing I like), but I am still using it. Interesting. Could you explain why? Personally, I find the *expr/**expr syntax much simpler, so I'd be interested in knowing what motivates you to continu

Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Steven Bethard
Fuzzyman wrote: Steven Bethard wrote: [EMAIL PROTECTED] wrote: However, is there a good reason why default parameters aren't evaluated as the function is called? (apart from efficiency and backwards compatibility)? So, one of my really common use cases that takes advantage of the fact that de

Re: list IndexError

2004-12-23 Thread Steven Bethard
Steven Bethard wrote: Ishwor wrote: i am trying to remove an item 'e' from the list l I thought it might be helpful to code some of the alternatives you've been given and look at the timings to put things into perspective. Corrected timings[1] using: $ python -m timeit -s

Re: list IndexError

2004-12-23 Thread Steven Bethard
Mike C. Fletcher wrote: Ah, my mistake, I missed the [:] after the source argument that was taking a copy... which brings up the question, how many other people would miss it? Too many. This is why I greatly prefer list(lst) to lst[:] It's also clearer to me. Do I really want a "slice" of

Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Steven Bethard
Fuzzyman wrote: Steven Bethard wrote: So, one of my really common use cases that takes advantage of the fact that default parameters are evaluated at function definition time: def foo(bar, baz, matcher=re.compile(r'...')): ... text = matcher.sub(r'...', text) ... Sure

Re: list IndexError

2004-12-23 Thread Steven Bethard
Grant Edwards wrote: Wouldn't the clearest way to get a copy would be to do something like: copy(lst) # I still think copy.copy() is a bit verbose... True, true. Maybe you could lobby for copy as a builtin in Python 3000? Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: Lambda going out of fashion

2004-12-23 Thread Steven Bethard
Jp Calderone wrote: On Thu, 23 Dec 2004 10:19:33 -0600, Skip Montanaro <[EMAIL PROTECTED]> wrote: While I'm sure it can be done, I'd hate to see a non-trivial Python program written with lambda instead of def. What, like this? [snip horrible lambda expression] OTOH, maybe that's still trivial,

Re: list Integer indexing dies??

2004-12-23 Thread Steven Bethard
Ishwor wrote: On Thu, 23 Dec 2004 13:33:16 -0300, Batista, Facundo <[EMAIL PROTECTED]> wrote: [Ishwor] #- > What should 035[0] cough up? Be carefull it should #- #- >>>035[0] #- 3 # my own opinion. #- #- > cough up the same as 29[0]. #- #- >>>29[0] #- 2 #again my own opinion Be aware th

copying builtin types (WAS: list IndexError)

2004-12-23 Thread Steven Bethard
Grant Edwards wrote: I would have guessed that calling list() on a list was a noop. I would be wrong. Surprised, but wrong. I guess it's probably worth pointing out that most builtin mutable types can be copied using the type constructor: py> def check(obj): ... copy = type(obj)(obj) ...

Re: Lambda going out of fashion

2004-12-23 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I have this book called TEXT PROCESSING IN PYTHON by David Mertz on hand, it is a good book and in the first chapter it is really a show room for higher-order functions which I may now cite to remind you of the FLEXIBILITY of this keyword. I'm not exactly sure what you mean

Re: Keyword arguments - strange behaviour?

2004-12-25 Thread Steven Bethard
Fuzzyman wrote: It wasn't that part of the example that I thought was over complex. (although it's not a 'pattern' I use often). You suggested that if we had dynamic evaluation of default values, you would have to replace it with : class foo(object): matcher=re.compile(r'...') def __new__(sel

Re: IDLE problem :-(

2004-12-25 Thread Steven Bethard
Ishwor wrote: I don't know if this has been a problem with other people using IDLE but when i press the home key then the cursor jumps to the beginning of the line and not after the prompt. If google prints the right indentation then here how i want the IDLE prompt to work -> |>>> |(r,b,g).__class

Re: Clearing the screen

2004-12-25 Thread Steven Bethard
Scott David Daniels wrote: Nick Coghlan wrote: Jeff Epler wrote: I don't know about idle, but the "real" python supports the PYTHONSTARTUP environment variable. I just tried it - IDLE ignores PYTHONSTARTUP, as does PythonWin (I just started using PYTHONSTARTUP to switch the standard prompt from

Re: A Revised Rational Proposal

2004-12-26 Thread Steven Bethard
Dan Bishop wrote: Mike Meyer wrote: PEP: XXX I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: Use PEP 257[1] docstring conventions, e.g. triple-quoted strings. Use PEP 8[2] naming conventions, e.g. na

Python 3000, zip, *args and iterators

2004-12-26 Thread Steven Bethard
So, as I understand it, in Python 3000, zip will basically be replaced with izip, meaning that instead of returning a list, it will return an iterator. This is great for situations like: zip(*[iter1, iter2, iter3]) where I want to receive tuples of (item1, item2, item3) from the iterables.

Re: list addition methods compared.

2004-12-26 Thread Steven Bethard
Ishwor wrote: Could u run the code in your machine and perhaps and let me know what the average speed is?? The code is - [snip code not using timeit] Are you aware of the timeit module? It can do most of these timings for you. Here's the code I used: -- extend.py ---

Re: Python 3000, zip, *args and iterators

2004-12-26 Thread Steven Bethard
Terry Reedy wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] So, as I understand it, in Python 3000, zip will basically be replaced with izip, meaning that instead of returning a list, it will return an iterator. I think it worth repeating tha

Re: A Revised Rational Proposal

2004-12-26 Thread Steven Bethard
Mike Meyer wrote: "John Roth" <[EMAIL PROTECTED]> writes: I'd suggest making them public rather than either protected or private. There's a precident with the complex module, where the real and imaginary parts are exposed as .real and .imag. This isn't addressed in the PEP, and is an oversight on

Re: Python 3000, zip, *args and iterators

2004-12-26 Thread Steven Bethard
Terry Reedy wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] I guess the point of my question is to find out if this kind of nice interaction of *args and iterators is something that's in the road-map. If it is, then maybe there are part

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

2004-12-27 Thread Steven Bethard
I wrote: Kent Johnson wrote: You can do the same thing using a PYTHONSTARTUP file - see http://docs.python.org/tut/node4.html#SECTION00424 You can change the prompts with import sys sys.ps1 = ' >>> ' sys.ps2 = ' ... ' Very cool. I didn't know about this. Does anyone know how to

Re: Tutorial problem

2004-12-27 Thread Steven Bethard
Rÿe9veillÿe9 wrote: Hello, I have just started doing the python tutorials and i tried to modify one of the exercises, it has to to with defining functions. I wanted the user to be able to enter an option and then get a print of the selected option. I also wanted to have an exit for the us

Re: Python 3000, zip, *args and iterators

2004-12-27 Thread Steven Bethard
Raymond Hettinger wrote: [Steven Bethard] What I would prefer is something like: >>> zip(*g(4)) >>> x, y, z = zip(*g(4)) >>> x, y, z (, at ...) 2. It is instructive to look at Guido's reactions to other *args proposals. His receptivity to a,b,*c=it wanes whenev

Re: objects as mutable dictionary keys

2004-12-27 Thread Steven Bethard
Peter Maas wrote: This strikes me because if one can do this with instances of user defined classes why not with lists? Trying to use lists as dict keys yields "TypeError: list objects are unhashable". So why are list objects unhashable and user defined objects hashable? For user defined objects ha

Re: objects as mutable dictionary keys

2004-12-27 Thread Steven Bethard
Peter Maas wrote: Steven Bethard schrieb: If lists were hashable, new programmers to Python would almost certainly make mistakes like: py> d = {[1, 2, 3]: 'abc'} > The coder here almost certainly *doesn't* want that list to be compared > by id. The only way to get

Re: Confusion About Classes

2004-12-27 Thread Steven Bethard
flamesrock wrote: Hi, I've been playing like mad with all sorts of python modules..but I still can't seem to get my head around the proper use of a class and self. The question stems from this code I made(snippet): [snip misaligned code] When posting to c.l.py it's greatly appreciated if you use sp

Re: argument type

2004-12-27 Thread Steven Bethard
It's me wrote: A newbie question. How can I tell from within a function whether a particular argument is a sigular type, or a complex type? For instance, in: def abc(arg1) How do I know if arg1 is a single type (like a number), or a list? In C++, you would do it with function overloading. If a

Re: argument type

2004-12-27 Thread Steven Bethard
It's me wrote: Steve, The argument I wish to pass is either one string, or a list of strings, or a tuple of strings. For instance, I have: def abc(arg1, arg2, arg3) Let say that I expect arg1 and arg3 to be a number, and arg2 can be either one string, or a bunch of strings and I need to do some

Re: argument type

2004-12-27 Thread Steven Bethard
It's me wrote: "It's me" <[EMAIL PROTECTED]> wrote in message news:EO6Ad.3296> I need to look up and see what: if not isinstance(arg2, basestring): does. Okay, I got the idea there. Now, what if arg2 is not a string but either a number or a bunch of numbers? Using your method, can I say so

Re: Keyword arguments - strange behaviour?

2004-12-28 Thread Steven Bethard
Fuzzyman wrote: I see. I may be wrong on this... *but* I thought the only time when a variable defined in the same scope as a function wouldn't be available in the same namespace is when the function is a global but the variable isn't ? Sorta depends on what you mean by "available in the same names

Re: built-in 'property'

2004-12-28 Thread Steven Bethard
Stian Søiland wrote: On 2004-12-28 12:05:20, [EMAIL PROTECTED] wrote: class NOTOK(object): def __init__(self): self.__x = 0 self.x = property(self.getx, self.setx, self.delx, "I'm the 'x' property.") def getx(self): return self.__x - 5 def setx(self, value): self

Re: built-in 'property'

2004-12-28 Thread Steven Bethard
Steven Bethard wrote: I seem to be missing some of the messages on this thread, but while we're talking about properties, it's probably instructive to remind people that the functions passed to the property function are not redefinable in subclasses: py> class D(C): ...

consequences of not calling object.__init__?

2004-12-28 Thread Steven Bethard
So when I'm writing a class and I define an __init__ method, I sometimes haven't called object.__init__, e.g.: class C(object): def __init__(self, x): self.x = x instead of class C(object): def __init__(self, x): super(C, self).__init__()

Re: consequences of not calling object.__init__?

2004-12-28 Thread Steven Bethard
John Lenton wrote: in the code that follows, instances of E haven't been through D's rigorous initiation process .class C(object): .def __init__(self): .print "C" . .class D(object): .def __init__(self): .print "D" .super(D, self).__init__

Re: A scoping question

2004-12-28 Thread Steven Bethard
It's me wrote: This must be another newbie gotchas. Consider the following silly code, let say I have the following in file1.py: #= import file2 global myBaseClass myBaseClass = file2.BaseClass() myBaseClass.AddChild(file2.NextClass()) #= and in file2.py, I have: #==

Re: A scoping question

2004-12-28 Thread Steven Bethard
It's me wrote: This must be another newbie gotchas. Consider the following silly code [snip tightly coupled code] A few options that also might work better than such tightly coupled modules: file1.py import file2 myBaseClass = file2.BaseClass() class NextCl

naming conventions (WAS: A scoping question)

2004-12-28 Thread Steven Bethard
It's me wrote: #= import file2 global myBaseClass myBaseClass = file2.BaseClass() myBaseClass.AddChild(file2.NextClass()) #= [snip] #= global myBaseClass class BaseClass: def __init__(self): self.MyChilds = [] ... def AddChild(NewChild):

Re: objects as mutable dictionary keys

2004-12-28 Thread Steven Bethard
Peter Maas wrote: Peter Maas schrieb: There was a huge and sometimes heated debate about tuples, lists and dictionaries recently, and the mainstream opinion was that dictionary keys must not be mutable, so lists are not allowed as dictionary keys. Warning, long posting (~ 100 lines) [snip summary]

Re: argument type

2004-12-28 Thread Steven Bethard
Doug Holton wrote: It's me wrote: The argument I wish to pass is either one string, or a list of strings, or a tuple of strings. def seq(x): if hasattr(x,"__iter__"): return x else: return (x,) def abc(arg1, arg2, arg3): for item in seq(arg2): print item

Re: Other notes

2004-12-28 Thread Steven Bethard
[EMAIL PROTECTED] wrote: 4) The printf-style formatting is powerful, but I still think it's quite complex for usual purposes, and I usually have to look its syntax in the docs. I think the Pascal syntax is nice and simpler to remember (especially for someone with a little Pascal/Delphi experience ^

Re: Other notes

2004-12-28 Thread Steven Bethard
Andrew Dalke wrote: I must say it's getting pretty annoying to say things like "when would this be useful?" and "have you read the documentation?" for your statements. I'll second that. Please, "Bearophile", do us the courtesy of checking (1) Google groups archive of the mailing list: http://group

calling functions across threads

2004-12-29 Thread Steven Bethard
I'm playing around with some threading stuff right now, and I'm having a little trouble calling a function from one thread that affects another. Here's my setup: py> import os, threading, time py> def write(file_in, input_lines): ... for line in input_lines: ... time.sleep(0.5) ...

Re: calling functions across threads

2004-12-29 Thread Steven Bethard
Thomas Rast wrote: Steven Bethard <[EMAIL PROTECTED]> writes: I get the correct output, but if you run this yourself, you'll see that the numbers 1 through 10 aren't printed in sync with the writes (i.e. every half second); they're all printed at the end. Could someone e

Re: calling functions across threads

2004-12-29 Thread Steven Bethard
Fernando Perez wrote: Steven Bethard wrote: I get the correct output, but if you run this yourself, you'll see that the numbers 1 through 10 aren't printed in sync with the writes (i.e. every half second); they're all printed at the end. Could someone explain to me why this happe

Re: Python 3000, zip, *args and iterators

2004-12-29 Thread Steven Bethard
Raymond Hettinger wrote: [Steven Bethard] I'm just suggesting that in a function with a *args in the def, the args variable be an iterator instead of a tuple. So people would lose the useful abilities to check len(args) or extract an argument with args[1]? No more than you lose these abil

Re: calling functions across threads

2004-12-29 Thread Steven Bethard
Fernando Perez wrote: Steven Bethard wrote: Fernando Perez wrote: Steven Bethard wrote: I get the correct output, but if you run this yourself, you'll see that the numbers 1 through 10 aren't printed in sync with the writes (i.e. every half second); they're all printed at the end.

Re: Confusion About Classes

2004-12-29 Thread Steven Bethard
M.E.Farmer wrote: there are no variables in python While it's true that in Python it's more appropriate to talk about names and bindings instead of variables and values, there is a parallel, and you can get a fair distance without having to fully convert to the names/bindings terminology. That

Re: Securing a future for anonymous functions in Python

2004-12-30 Thread Steven Bethard
Jeff Shannon wrote: My thesis here is that one of the most common (legitimate) uses of lambda is as an adapter, to create an intermediary that allows a callable with a given signature to be used in places where a different signature is expected -- that is, altering the number or order of argume

Re: built-in 'property'

2004-12-30 Thread Steven Bethard
Sean Ross wrote: I'll note that it is possible to change the built-in property (in a backward compatible manner) to be used as a decorator for this idiom, to redefine parts of properties in sub-classes, and to provide default get/set/del methods. Is there a recipe or blog or something somewhere tha

what is lambda used for in real code?

2004-12-30 Thread Steven Bethard
I thought it might be useful to put the recent lambda threads into perspective a bit. I was wondering what lambda gets used for in "real" code, so I grepped my Python Lib directory. Here are some of the ones I looked, classified by how I would rewrite them (if I could): * Rewritable as def st

Re: Pre-PEP: Dictionary accumulator methods

2005-03-27 Thread Steven Bethard
Michele Simionato wrote: I am surprised nobody suggested we put those two methods into a separate module (say dictutils or even UserDict) as functions: from dictutils import tally, listappend tally(mydict, key) listappend(mydict, key, value) Sorry to join the discussion so late (I've been away from

Re: Pre-PEP: Dictionary accumulator methods

2005-03-27 Thread Steven Bethard
Michele Simionato wrote: FWIW, here is my take on the defaultdict approach: def defaultdict(defaultfactory, dictclass=dict): class defdict(dictclass): def __getitem__(self, key): try: return super(defdict, self).__getitem__(key) except KeyError:

Re: Specifying __slots__ in a dynamically generated type

2005-03-27 Thread Steven Bethard
Ron Garret wrote: I need to dynamically generate new types at run time. I can do this in two ways. I can use the "type" constructor, or I can generate a "class" statement as a string and feed that to the exec function. The former technique is much cleaner all else being equal, but I want to b

Re: Specifying __slots__ in a dynamically generated type

2005-03-27 Thread Steven Bethard
Ron Garret wrote: In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: Why don't you just write a function to create class objects? def f(*params): class C(...): ... # based on params return C I suppose I could. When I originally started wr

Re: Overriding methods in classes you don't control

2005-03-27 Thread Steven Bethard
Alex VanderWoude wrote: Basically I want to change wxFrame.__init__ so that it looks sort of like this: def __init__(self, *args, **kwargs): # Some enhancements here. # The original code of this method, including the call to its ancestor. # Some more enhancements here. A

Re: How to organize source code and "import"s???

2005-03-27 Thread Steven Bethard
Tian wrote: I also have some problem about the "import". How should I design my packages? Say, I have all code locates at c:\projects\sami, "c:\project" is in my PYTHONPATH environment variable. Suppose my folder structure is like this: c: projects\ <-this directory is in PYTHONPATH

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