Re: [Python-Dev] comprehension abbreviation (was: Adding any() and all())
> - Before anybody asks, I really do think the reason this is requested > at all is really just to save typing; there isn't the "avoid double > evaluation" argument that helped acceptance for assignment operators > (+= etc.), and I find redability is actually improved with 'for'. I'd like it, and my reason isn't "just to save typing". There are two reasons. 1 Some bit of my brain is convinced that [x in stuff if condition] is the Right Syntax and keeps making me type it even though I know it doesn't work. 2 Seeing [x for x in stuff if condition] triggers my internal duplicated-stuff alarm, and it's distracting, in the same sort of way as it's distracting in C or C++ seeing Thing thing = new Thing(); with the type name appearing three times. Incidentally, while it's quite true that you only save 4 characters if you use "x" for your variable name, some of us do sometimes like to use something more informative even as a very local loop-index variable (which is what this basically is). -- g ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote:
But I think the logical consequence of your approach would be that
sum([]) should raise an exception rather than return 0, which would be
backwards incompatible. Because if the identity element has a default
value, the default value should be used exactly as if it were
specified explicitly.
Unfortunately my proposal is also backwards incompatible, since
currently sum([1,1], 40) equals 42.
Somewhat ugly, but backwards compatible:
sentinel = object()
def sum(iterable, initial=sentinel):
itr = iter(iterable)
if initial is not sentinel:
# Initial value provided, so use it
value = initial
else:
try:
first = itr.next()
except StopIteration:
# Empty iterable, return 0 for backwards compatibility
# Also correct for standard numerical use
return 0
# Assume default constructor returns the additive identity
value = type(first)()
value += first
# Add the elements
for item in itr:
value += item
return value
Py> sum([])
0
Py> seq = ([1], [2], [3])
Py> sum(seq)
[1, 2, 3]
Py> seq
([1], [2], [3])
Py> seq = ('1', '2', '3')
Py> sum(seq)
'123'
Py> seq
('1', '2', '3')
Cheers,
Nick.
--
Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] can we stop pretending _PyTyple_Lookup is internal?
It's needed to implement things that behave like instance methods, for instance, and I notice that at at least some point in the past Zope3 has used the function with a note attached saying "Guido says this is OK". Also, the context is that I want to submit a patch to PyObjC using the function, and doing a little digging revealed that PyObjC already has a copy & paste copy of _PyType_Lookup, presumably to avoid using an internal API. I don't think this does anyone any good. Thoughts? Cheers, mwh -- I wouldn't trust the Anglo-Saxons for much anything else. Given they way English is spelled, who could trust them on _anything_ that had to do with writing things down, anyway? -- Erik Naggum, comp.lang.lisp ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] func.update_meta (was: @deprecated)
Neat! But please add something to the __doc__ so we can also see it was changed. E.g. self.__doc__ = other.__doc__ + os.linesep + "*** deprecated ***" On 12 mrt 2005, at 5:25, Nick Coghlan wrote: I like "update_meta" Patch against current CVS added to SF with the behaviour: def update_meta(self, other): self.__name__ = other.__name__ self.__doc__ = other.__doc__ self.__dict__.update(other.__dict__) ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] comprehension abbreviation (was: Adding any() and all())
On Mar 14, 2005, at 10:57, Gareth McCaughan wrote: of way as it's distracting in C or C++ seeing Thing thing = new Thing(); with the type name appearing three times. I think you can't possibly see this in C:-), you need a star there in C++, and you need to avoid the 'new' (just calling Thing() should do it -- maybe you're commixing with Java?), but still, I do agree it looks uncool... no doubt a subtle ploy by Java and C++ designers to have you use, instead, the preferable interface-and-factory idioms such as: IThing thing* = thingFactory(); rather than declaring and instantiating concrete classes, which is just _so_ three years ago;-) Back to the Python world, I don't particularly love [x for x in ...] by any means, but I surely hope we're not tweaking the syntax for such tiny gains in the 2.4 -> 2.5 transition. Wasn't 2.5 "supposed to be" mostly about standard library reorganizations, enhancements, etc? Were there some MAJOR gains to be had in syntax additions, guess that could be bent, but snipping the [ for ...] leading part seems just such a tiny issue. (If the discussion is about 3.0, and I missed the indication of that, I apologize). Alex ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Mar 14, 2005, at 11:20, Nick Coghlan wrote: ... Somewhat ugly, but backwards compatible: I realize you're mostly talking semantics, not implementation, but, as long as we're at it, could we pretty please have back the optimization indicated by...: # Add the elements if isinstance(value, basestring): return value + ''.join(itr) for item in itr: value += item return value ...? This doesn't break bw compat since currently when value's a string sum would raise an exception... Alex ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Greg Ewing wrote: Guido van Rossum wrote: - the identity (defaulting to 0) if the sequence is empty - the first and only element if the sequence only has one element - (...(((A + B) + C) + D) + ...) if the sequence has more than one element While this might be reasonable if the identity argument is not specified, I think that if an identity is specified, it should be used even if the sequence is non-empty. The reason being that the user might be relying on that to get the semantics he wants. Think of the second argument as "accumulator object" rather than "identity". +1 for Greg I think of the second argument as a running total which defaults to the operator's neutral element. Perhaps the second argument should not be optional to emphasise this. After all, there's much more to sum() than numbers. --eric ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] comprehension abbreviation (was: Adding any() and all())
Gareth McCaughan wrote: I'd like it, and my reason isn't "just to save typing". There are two reasons. 1 Some bit of my brain is convinced that [x in stuff if condition] is the Right Syntax and keeps making me type it even though I know it doesn't work. 2 Seeing [x for x in stuff if condition] triggers my internal duplicated-stuff alarm, and it's distracting, in the same sort of way as it's distracting in C or C++ seeing The full syntax is: [ f(x) for x in seq if pred(x) ] being allowed to write 'x' instead of 'identity(x)' is already a shortcut, just as dropping the conditional part. Remember we're doing set theory stuff here. IMHO we should follow its notation conventions as much as we can. --eric ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] can we stop pretending _PyTyple_Lookup is internal?
Hi Michael,
> ... _PyType_Lookup ...
There has been discussions about copy_reg.py and at least one other place in
the standard library that needs this; it is an essential part of the
descriptor model of new-style classes. In my opinion it should be made part
not only of the official C API but the Python one too, e.g. as a method of
'type' instances: type(x).lookup('name')
Armin
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] comprehension abbreviation (was: Adding any() and all())
On Monday 2005-03-14 12:09, Alex Martelli wrote: > > On Mar 14, 2005, at 10:57, Gareth McCaughan wrote: > > > of way as it's distracting in C or C++ seeing > > > > Thing thing = new Thing(); > > > > with the type name appearing three times. > > I think you can't possibly see this in C:-), you need a star there in > C++, and you need to avoid the 'new' (just calling Thing() should do it > -- maybe you're commixing with Java?), but still, I do agree it looks > uncool... no doubt a subtle ploy by Java and C++ designers to have you > use, instead, the preferable interface-and-factory idioms such as: Er, sorry about the various slips of detail. And I don't even use Java. Bah! (But it looks even worse without the "new" intervening...) > IThing thing* = thingFactory(); > > rather than declaring and instantiating concrete classes, which is just > _so_ three years ago;-) :-) > Back to the Python world, I don't particularly love [x for x in ...] by > any means, but I surely hope we're not tweaking the syntax for such > tiny gains in the 2.4 -> 2.5 transition. Wasn't 2.5 "supposed to be" > mostly about standard library reorganizations, enhancements, etc? Were > there some MAJOR gains to be had in syntax additions, guess that could > be bent, but snipping the [ for ...] leading part seems just such > a tiny issue. (If the discussion is about 3.0, and I missed the > indication of that, I apologize). When I say I'd like it, I don't mean "we should change it now", only that it would be nice for it to be there. Stability matters more than optimality sometimes, and now may well be such a time. -- g ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] comprehension abbreviation (was: Adding any() and all())
On Monday 2005-03-14 12:42, Eric Nieuwland wrote:
> Gareth McCaughan wrote:
>
> > I'd like it, and my reason isn't "just to save typing".
> > There are two reasons.
> >
> > 1 Some bit of my brain is convinced that [x in stuff if condition]
> > is the Right Syntax and keeps making me type it even though
> > I know it doesn't work.
> >
> > 2 Seeing [x for x in stuff if condition] triggers my internal
> > duplicated-stuff alarm, and it's distracting, in the same sort
> > of way as it's distracting in C or C++ seeing
>
> The full syntax is:
> [ f(x) for x in seq if pred(x) ]
> being allowed to write 'x' instead of 'identity(x)' is already a
> shortcut, just as dropping the conditional part.
>
> Remember we're doing set theory stuff here. IMHO we should follow its
> notation conventions as much as we can.
I'm well aware of what the full syntax is; being allowed to
write "x" instead of "identity(x)" is *not* a "shortcut" but
a perfectly straightforward unexceptional instance of the
usual syntax; list comprehensions already have neither the
syntax nor the semantics of set-theorists' comprehensions;
and in fact no set theorist would be at all troubled by seeing
{ x in S : predicate(x) }
which is the nearest equivalent in mathematical notation
for the abbreviated comprehension expressions being discussed.
Other than that, I quite agree :-).
--
g
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] can we stop pretending _PyTyple_Lookup is internal?
Armin Rigo <[EMAIL PROTECTED]> writes:
> Hi Michael,
>
>> ... _PyType_Lookup ...
>
> There has been discussions about copy_reg.py and at least one other place in
> the standard library that needs this; it is an essential part of the
> descriptor model of new-style classes. In my opinion it should be made part
> not only of the official C API but the Python one too, e.g. as a method of
> 'type' instances: type(x).lookup('name')
Yes, this would be good too. The patch should be trivial; I guess a
little work is required to ensure b/w compat, but not very much
really.
Cheers,
mwh
--
how am I expected to quit smoking if I have to deal with NT
every day-- Ben Raia
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] func.update_meta (was: @deprecated)
Eric Nieuwland wrote: Neat! But please add something to the __doc__ so we can also see it was changed. E.g. self.__doc__ = other.__doc__ + os.linesep + "*** deprecated ***" Decorators that alter the signature, or wish to change the docstring can make their modifications after copying from the original (or simply not copy from the original in the first place). E.g: def deprecated(orig): def f(*args, **kwds): #Emit warning here return orig(*args, **kwds) f.update_meta(orig) f.__doc__ = "*** Deprecated *** " + f.__doc__ return f Any such changes are outside the purview of a metadata transfer method, though, since they're highly decorator dependent. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] (no subject)
Nick Coghlan writes: > Patch against current CVS added to SF with the behaviour: > >def update_meta(self, other): > self.__name__ = other.__name__ > self.__doc__ = other.__doc__ > self.__dict__.update(other.__dict__) Nice... thanks. But I have to ask: is this really the right set of metadata to be updating? Here are a few things that perhaps ought be copied by update_meta: f.__name__ (already included) f.__doc__ (already included) f.__dict__ (already included) f.__module__ (probably should include) f.func_code.co_filename (to match f.__name__, but I'd leave it alone) there's also the annoying fact that in IDLE (and in some other python-aware IDEs) one can see the argument signature for a function as a "tool tip" or other hint. Very handy that, but if a decorator is applied then all you will see is "func(*args, **kwargs)" which is less than helpful. I'm not sure whether this CAN be duplicated... I believe it is generated by examining the following: f.func_code.co_argcount f.func_code.co_varnames f.func_code.co_flags & 0x4 f.func_code.co_flags & 0x8 ...and I suspect (experimentation seems to confirm this) that if you mangle these then the code object won't work correctly. If anyone's got a suggestion for fixing this, I'd love to hear it. -- Michael Chermside ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Alex Martelli wrote:
On Mar 14, 2005, at 11:20, Nick Coghlan wrote:
...
Somewhat ugly, but backwards compatible:
I realize you're mostly talking semantics, not implementation, but, as
long as we're at it, could we pretty please have back the optimization
indicated by...:
It turns out the sentinel value isn't really needed either:
def sum(*args):
itr = iter(args[0])
try:
value = args[1]
except IndexError:
# No start value, so use the type of the first element
try:
first = itr.next()
except StopIteration:
# Empty iterable, return 0 for backwards compatibility
# When summing over something other than a sequence of
# numbers, giving an initial value is a good idea.
return 0
# Use default constructor to get initial value
value = type(first)()
value += first
# Special case optimisation of strings
if isinstance(value, basestring):
# Rely on ''.join promoting to unicode if needed
return value + ''.join(itr)
# Add the elements
for item in itr:
value += item
return value
I'm not sure how much we really gain though - at the moment, using sum() for
anything other than numbers gives an immediate exception. With the behaviour
above, it appears to work, but will return 0 for an empty sequence instead of
the additive identity of the desired type (e.g. "" or []). So the error will
turn up somewhere else, instead of as an explicit exception at the point of origin.
Maybe what we really should be doing is trapping the TypeError, and generating a
more meaningful error message.
E.g.
Py> def sum(seq, initial=0):
... itr = iter(seq)
... try:
... first = itr.next()
... except StopIteration:
... return 0
... value = initial
... try:
... value += first
... except TypeError:
... raise TypeError("Cannot add first element %r to initial value %r" % (fir
st, value))
... for item in itr:
... value += item
... return value
...
Py> seq = ([1], [2], [3])
Py> sum(seq)
Traceback (most recent call last):
File "", line 1, in ?
File "", line 11, in sum
TypeError: Cannot add first element [1] to initial value 0
Py> sum(seq, [])
[1, 2, 3]
Py> seq = ('1', '2', '3')
Py> sum(seq)
Traceback (most recent call last):
File "", line 1, in ?
File "", line 11, in sum
TypeError: Cannot add first element '1' to initial value 0
Py> sum(seq, '')
'123'
--
Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] comprehension abbreviation (was: Adding any() an d all())
Title: RE: [Python-Dev] comprehension abbreviation (was: Adding any() and all()) [Gareth McCaughan] #- 1 Some bit of my brain is convinced that [x in stuff if condition] #- is the Right Syntax and keeps making me type it even though #- I know it doesn't work. My brain says: '"x in stuff" returns a bool, so we have "[bool if condition]"', and then my brain crash generating a core dump... . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] Exception needed: Not enough arguments to PyArg_ParseTuple
I had PyArg_ParseTuple(args, "s#s#i:compare", &p1, &bytes1, &p2, &bytes2) in a program. There are not enough arguments to PyArg_ParseTuple. Does PyArg_ParseTuple know how many arguments it is getting? If so, I suggest that an exception should be raised here. ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] (no subject)
At 05:34 AM 3/14/05 -0800, Michael Chermside wrote: Nice... thanks. But I have to ask: is this really the right set of metadata to be updating? Here are a few things that perhaps ought be copied by update_meta: f.__name__ (already included) f.__doc__ (already included) f.__dict__ (already included) f.__module__ (probably should include) f.func_code.co_filename (to match f.__name__, but I'd leave it alone) Leave __module__ alone, too, unless you want to play havoc with any inspection tools looking for the source code. there's also the annoying fact that in IDLE (and in some other python-aware IDEs) one can see the argument signature for a function as a "tool tip" or other hint. Very handy that, but if a decorator is applied then all you will see is "func(*args, **kwargs)" which is less than helpful. I'm not sure whether this CAN be duplicated... I believe it is generated by examining the following: f.func_code.co_argcount f.func_code.co_varnames f.func_code.co_flags & 0x4 f.func_code.co_flags & 0x8 ...and I suspect (experimentation seems to confirm this) that if you mangle these then the code object won't work correctly. If anyone's got a suggestion for fixing this, I'd love to hear it. One solution is to have a __signature__ attribute that's purely documentary. That is, modifying it wouldn't change the function's actual behavior, so it could be copied with update_meta() but then modified by the decorator if need be. __signature__ would basically be a structure like the one returned by inspect.getargspec(). Also, 'instancemethod' would have a __signature__ equal to its im_func.__signature__ with the first argument dropped off, thus making it easy to introspect wrapper chains. I discussed this approach with Guido in private e-mail a few months back during discussion about an article I was writing for DDJ about decorators. We also discussed something very similar to 'update_meta()', but never settled on a name. Originally he wanted me to PEP the whole thing, but he wanted it to include optional type declaration info, so you can probably see why I haven't done anything on that yet. :) However, if we can define a __signature__ format that allows for type declaration, I imagine there'd be little problem with moving forward on it. ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Exception needed: Not enough arguments to PyArg_ParseTuple
"Edward C. Jones" <[EMAIL PROTECTED]> writes: > I had > > PyArg_ParseTuple(args, "s#s#i:compare", &p1, &bytes1, &p2, &bytes2) > > in a program. There are not enough arguments to PyArg_ParseTuple. Does > PyArg_ParseTuple know how many arguments it is getting? I don't think so. > If so, I suggest that an exception should be raised here. I think you'd need to do battle with ISO C first. Cheers, mwh -- Counting lines is probably a good idea if you want to print it out and are short on paper, but I fail to see the purpose otherwise. -- Erik Naggum, comp.lang.lisp ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] (no subject)
"Phillip J. Eby" <[EMAIL PROTECTED]> writes: > At 05:34 AM 3/14/05 -0800, Michael Chermside wrote: >>Nice... thanks. But I have to ask: is this really the right set of metadata to >> be updating? Here are a few things that perhaps ought be copied by >> update_meta: >> >> f.__name__ (already included) >> f.__doc__ (already included) >> f.__dict__ (already included) >> f.__module__ (probably should include) >> f.func_code.co_filename (to match f.__name__, but I'd leave it alone) > > Leave __module__ alone, too, unless you want to play havoc with any > inspection tools looking for the source code. > > >>there's also the annoying fact that in IDLE (and in some other python-aware >>IDEs) one can see the argument signature for a function as a "tool tip" >>or other hint. Very handy that, but if a decorator is applied then all >>you will see is "func(*args, **kwargs)" which is less than helpful. I'm >>not sure whether this CAN be duplicated... I believe it is generated by >>examining the following: >> >> f.func_code.co_argcount >> f.func_code.co_varnames >> f.func_code.co_flags & 0x4 >> f.func_code.co_flags & 0x8 >> >>...and I suspect (experimentation seems to confirm this) that if you mangle >>these then the code object won't work correctly. If anyone's got a >>suggestion for fixing this, I'd love to hear it. > > One solution is to have a __signature__ attribute that's purely > documentary. That is, modifying it wouldn't change the function's > actual behavior, so it could be copied with update_meta() but then > modified by the decorator if need be. __signature__ would basically > be a structure like the one returned by inspect.getargspec(). Also, > 'instancemethod' would have a __signature__ equal to its > im_func.__signature__ with the first argument dropped off, thus making > it easy to introspect wrapper chains. Another possibility (ugly, maybe) would be to create sourcecode with the function signature that you need, and compile it. inspect.getargspec() and inspect.formatargspec can do most of the work. Thomas ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] (no subject)
At 04:35 PM 3/14/05 +0100, Thomas Heller wrote: Another possibility (ugly, maybe) would be to create sourcecode with the function signature that you need, and compile it. inspect.getargspec() and inspect.formatargspec can do most of the work. I've done exactly that, for generic functions in PyProtocols. It's *very* ugly, and not something I'd wish on anyone needing to write a decorator. IMO, inspect.getargspec() shouldn't need to be so complicated; it should just return an object's __signature__ in future Pythons. Also, the 'object' type should have a __signature__ descriptor that returns the __signature__ of __call__, if present. And types should have a __signature__ that returns the __init__ or __new__ signature of the type. Finally, C methods should have a way to define a __signature__ as well. At that point, any callable object has an introspectable __signature__, which would avoid the need for every introspection framework or documentation tool having to rewrite the same old type dispatching code to check if it's an instancemethod, an instance with a __call__, a type, etc. etc. in order to find the real function and how to modify what getargspec() returns. ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Tue, 15 Mar 2005 00:05:32 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
[...]
> Maybe what we really should be doing is trapping the TypeError, and
> generating a
> more meaningful error message.
>
> E.g.
>
[...]
> ... try:
> ... value += first
> ... except TypeError:
> ... raise TypeError("Cannot add first element %r to initial value %r" %
> (first, value))
No, no, no! NO! Never catch a general exception like that and replace
it with one of your own. That can cause hours of debugging pain later
on when the type error is deep down in the bowels of the += operation
(or perhaps deep down inside something *it* invoked).
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] (no subject)
Phillip J. Eby wrote:
[SNIP]
One solution is to have a __signature__ attribute that's purely
documentary. That is, modifying it wouldn't change the function's
actual behavior, so it could be copied with update_meta() but then
modified by the decorator if need be. __signature__ would basically be
a structure like the one returned by inspect.getargspec(). Also,
'instancemethod' would have a __signature__ equal to its
im_func.__signature__ with the first argument dropped off, thus making
it easy to introspect wrapper chains.
I discussed this approach with Guido in private e-mail a few months back
during discussion about an article I was writing for DDJ about
decorators. We also discussed something very similar to
'update_meta()', but never settled on a name. Originally he wanted me
to PEP the whole thing, but he wanted it to include optional type
declaration info, so you can probably see why I haven't done anything on
that yet. :)
However, if we can define a __signature__ format that allows for type
declaration, I imagine there'd be little problem with moving forward on it.
It could be as simple as just a bunch of tuples. The following (assuming *args
and **kwargs are not typed; don't remember if they can be)::
def foo(pos1, pos2:int, key1="hi", key2=42:int, *args, **kwargs): pass
could be::
((('pos1', None), ('pos2', int)), (('key1', "hi", None), ('key2', 42, int)),
'args', 'kwargs')
In case the format is not obvious, just a bunch of tuples grouped based on
whether they are positional, keyword, or one of the collecting arguments. For
positional arguments, have a two-item tuple consisting of the argument name and
the possible type. For keyword, 3-item tuple with name, default value, and
possible type. Lacking *args and/or **kwargs could just be set to None for
those tuple positions.
Since this is mainly for introspection tools the format can stand to be verbose
and not the easiest thing to read by eye, but it must contain all possible info
on the arguments. And if actual execution does not use this slot, as Phillip
is suggesting, but it is only for informative purposes we could make it
optional. It could also be set it to a descriptor that dynamically creates the
tuple when called based on the function passed into the descriptor at creation
time. This could be rolled into the update_meta (or whatever it ends up being
called) function.
-Brett
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] Python2.4.1c1 and win32com
Bug has been filed with id 1163244. regards, --Tim -Original Message- From: "Martin v. Lowis" [mailto:[EMAIL PROTECTED] Sent: Saturday, March 12, 2005 3:12 PM To: Leeuw van der, Tim Cc: [email protected] Subject: Re: [Python-Dev] Python2.4.1c1 and win32com Leeuw van der, Tim wrote: > The generated files crash the Python interpreter with Python 2.4 > > Under Python 2.4.1c1, They give a syntax error!? [...] So I think this needs to be investigated; please submit a bug report, including the Python file that causes the crash. Regards, Martin ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] code blocks using 'for' loops and generators
Greg Ewing <[EMAIL PROTECTED]> wrote: > > Brian Sabbey wrote: > > > How about something like below? In the same way > > that "self" is passed "behind the scenes" as the first argument, so can > > the thunk be. > > > > with stopwatch() result dt: > > a() > > b() > > print 'it took', dt, 'seconds to compute' > > Something like that would be better, yes. Maybe even just > >dt = stopwatch(): > a() > b() > > Whatever keyword is used is bound to not sound right > for some usages, so it would be best if no keyword > were needed at all. Since PEP 310 was already mentioned, can we just say that the discussion can be boiled down to different ways of spelling __enter__/__exit__ from PEP 310? If so, then if either one of you really want/need this kind of thing, maybe one of you should pick up the PEP, address the issues sufficiently, and make it happen. - Josiah ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
Kurt B. Kaiser wrote: Do you happen to remember the precise error message? "This installation package could not be opened." Ah, that you get if the file is already open. Do you run some shell extension that might want to look into the MSI file, or virus scanners? I also recall a KB article that the Indexing Service sometimes prevents files from being opened. Quadruple-click could also cause the problem, if you try to start multiple installers. If I wait for the download to complete and the virus check to finish, then it's AOK. That's why the third time was the charm. Ok, so it's likely incomplete download. Regards, Martin ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] code blocks using 'for' loops and generators
Josiah Carlson wrote: Since PEP 310 was already mentioned, can we just say that the discussion can be boiled down to different ways of spelling __enter__/__exit__ from PEP 310? It's not quite the same thing. PEP 310 suggests a mechanism with a fixed control flow -- do something on entry, do the code block, do something on exit. A general block-passing mechanism would give complete control to the function as to when and how to call the block. However, it's possible that if generators were enhanced with some means of allowing yield inside try-finally, then generators plus PEP 310 would cover most use cases: for-loops and generators when you want to loop, and PEP 310 when you don't. So rather than coming up with new syntax at this point, perhaps it would be better to concentrate on the problem of yield inside try-finally. Even if the finally can't be guaranteed to run under all conditions, I think it would be useful if it could be arranged so that for x in somegenerator(): ... raise Blather ... would caused any finallies that the generator was suspended inside to be executed. Then the semantics would be the same as if the for-loop-over-generator were implemented by passing a thunk to a function that calls it repeatedly. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Exception needed: Not enough arguments to PyArg_ParseTuple
Edward C. Jones wrote: I had PyArg_ParseTuple(args, "s#s#i:compare", &p1, &bytes1, &p2, &bytes2) in a program. There are not enough arguments to PyArg_ParseTuple. Does PyArg_ParseTuple know how many arguments it is getting? No. There is no standard way for a C function to find out how many parameters it has been passed, and most C implementations don't provide any way at all. That's why the calling interface to varargs functions invariably includes some way for the caller to indicate the number of arguments, such as a format string or a terminating NULL. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: But I think the logical consequence of your approach would be that sum([]) should raise an exception rather than return 0, which would be backwards incompatible. Because if the identity element has a default value, the default value should be used exactly as if it were specified explicitly. In that case I would argue in favour of keeping it the way it is, since... currently sum([1,1], 40) equals 42. ...seems quite reasonable to me. Or at least as reasonable as anything else. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] code blocks using 'for' loops and generators
be guaranteed to run under all conditions, I think it would be useful if it could be arranged so that for x in somegenerator(): ... raise Blather ... would caused any finallies that the generator was suspended inside to be executed. Then the semantics would be the same as if the for-loop-over-generator were implemented by passing a thunk to a function that calls it repeatedly. One difficulty is that one can never know if the user intends to still use the generator, like so: a = somegenerator() try: for x in a: raise Blather except: a.next() I think they only way you can really be sure .next() will not be called again is if the generator is no longer referenced. Someone submitted a patch once to execute "finallies" when the generator is __del__eted, but it was rejected for various reasons. In my original post in this thread I tried to provide a mechanism such as you describe by providing __call__ as an alternative to 'next', but now I am convinced that it is better to introduce a new syntax instead of re-using generators. Incidentally, passing the thunk "behind the scenes" as the first argument (as mentioned previously) allows one to avoid using lambda to do things such as sort (I hear lambdas are on the way out), while remaining anonymous: with x, y from a.sort(): value cmp(x.k1, y.k1) or (x.k2, y.k2) (or whatever the preferred syntax is) instead of: a.sort(lambda x,y : cmp(x.k1, y.k1) or (x.k2, y.k2)) Not that I find either form better than the other, but I do find both better than have to define a named function. I am going to see if I can make a PEP for this. -Brian ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] comprehension abbreviation
Eric Nieuwland wrote: The full syntax is: [ f(x) for x in seq if pred(x) ] > being allowed to write 'x' instead of 'identity(x)' is already a shortcut, That's a really strange way of looking at it. Unless you would also say that x = y is a shorthand for x = identity(y) Not that it's false, it just seems like a completely unnecessary layer of mental gymnastics... -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Eric Nieuwland wrote: Perhaps the second argument should not be optional to emphasise this. After all, there's much more to sum() than numbers. I think practicality beats purity here. Using it on numbers is surely an extremely common case. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
[Eric Nieuwland] >> Perhaps the second argument should not be optional to emphasise this. >> After all, there's much more to sum() than numbers. [Greg Ewing] > I think practicality beats purity here. Using it on > numbers is surely an extremely common case. I'd personally be delighted if sum() never worked on anything other than numbers. That makes it easy to understand, easy to document, easy to remember, obvious at first sight, and straightforward to implement. Everything a framework isn't, but it's not a bad thing to have *something* that actually means exactly what it looks like it says <0.5 wink>. ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] code blocks using 'for' loops and generators
Brian Sabbey wrote: be guaranteed to run under all conditions, I think it would be useful if it could be arranged so that for x in somegenerator(): ... raise Blather ... would caused any finallies that the generator was suspended inside to be executed. Then the semantics would be the same as if the for-loop-over-generator were implemented by passing a thunk to a function that calls it repeatedly. One difficulty is that one can never know if the user intends to still use the generator, like so: a = somegenerator() try: for x in a: raise Blather except: a.next() I think they only way you can really be sure .next() will not be called again is if the generator is no longer referenced. Someone submitted a patch once to execute "finallies" when the generator is __del__eted, but it was rejected for various reasons. In my original post in this thread I tried to provide a mechanism such as you describe by providing __call__ as an alternative to 'next', but now I am convinced that it is better to introduce a new syntax instead of re-using generators. Incidentally, passing the thunk "behind the scenes" as the first argument (as mentioned previously) allows one to avoid using lambda to do things such as sort (I hear lambdas are on the way out), while remaining anonymous: with x, y from a.sort(): value cmp(x.k1, y.k1) or (x.k2, y.k2) (or whatever the preferred syntax is) instead of: a.sort(lambda x,y : cmp(x.k1, y.k1) or (x.k2, y.k2)) Not that I find either form better than the other, but I do find both better than have to define a named function. Notice that syntax is the key issue here, it is not like it is hard to think a range of semantics for thunks/anonymous functions. In fact thunks can probably be just closures with some tweaks up to the yield issue. In fact if some unnatural (for Python POV likely) parentheses would be acceptable but they are very likely not, it is simple to devise syntaxes that allows anonymous functions pretty much everywhere. This would allow for some rather unwieldy code. OTOH a suite-based syntax for thunks can likely not work as a substitute of lambda for cases like: f(lambda: ..., ...) where the function is the first argument, and then there are further arguments. (Of course not-so-natural helper functions can be written to swap arguments around). Apart this one very hard problem, it would be nice to be able to define and pass more thunks simultaneously. In particular a more concise syntax for def setx(self, v): self._x = v def getx(self): return self._x x = property(getx,setx) was considered in the past discussions about the topic a worthy goal. regards ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] code blocks using 'for' loops and generators
Samuele Pedroni wrote:
OTOH a suite-based syntax for thunks can likely not work as a substitute of
lambda for cases like:
f(lambda: ..., ...)
where the function is the first argument, and then there are further
arguments.
I do not see why you say suite-based thunks cannot be used in the case in
which the function takes more than one argument. Using the syntax I
described earlier, they work in just that way:
def pickled_file(thunk, name):
...
new_data = thunk(pickle.load(f))
...
with greetings from pickled_file('greetings.pickle'):
...
value greetings
One can make an analogy with "self". Both the thunk and self can be
passed automatically as the first argument, and further arguments can
follow. In this way, functions that already take a thunk as a first
argument (such as sort) can be re-used without modification.
Apart this one very hard problem, it would be nice to be able to define
and pass more thunks simultaneously. In particular a more concise syntax for
def setx(self, v): self._x = v
def getx(self): return self._x
x = property(getx,setx)
was considered in the past discussions about the topic a worthy goal.
Here I can make another analogy with self. Just as python does not give
syntactic support for multiple dispatch because (I assume) it would
require major syntax changes for something that would be rarely used, I do
not think it is worth it to give syntactic support for multiple thunks.
If only a fraction "epsilon" of functions take a single thunk, then I
would guess that "epsilon**2" take two thunks, and it is not worth
creating syntax for such a small number of cases, especially if that
syntax compromises what would otherwise be a much cleaner syntax for the
single thunk case.
-Brian
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Mon, 14 Mar 2005 19:16:22 -0500, Tim Peters <[EMAIL PROTECTED]> wrote: > [Eric Nieuwland] > >> Perhaps the second argument should not be optional to emphasise this. > >> After all, there's much more to sum() than numbers. > > [Greg Ewing] > > I think practicality beats purity here. Using it on > > numbers is surely an extremely common case. [Tim Peters] > I'd personally be delighted if sum() never worked on anything other > than numbers. That makes it easy to understand, easy to document, > easy to remember, obvious at first sight, and straightforward to > implement. Everything a framework isn't, but it's not a bad thing to > have *something* that actually means exactly what it looks like it > says <0.5 wink>. Unfortunately this started when I claimed in my blog that sum() was a replacement for 80% of all reduce() uses. This was countered by someone who pointed out that without a 2nd argument it doesn't work for non-numbers that happen to implement __add__, and I'm not sure he was aware you could make it work *with* a 2nd argument (I know *I* had forgotten all about that :-). I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make "fixing" it impossible before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is only used for empty lists. Alex's use case for a nonzero 2nd argument: total = 0 for lst in sequence_of_lists: total = sum(lst, total) can be just as easily written like this: total = 0 for lst in sequence_of_lists: total += sum(lst) and I think that's actually clearer (since the reader doesn't have to know about the 2nd argument's meaning). -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1
"Martin v. Löwis" <[EMAIL PROTECTED]> writes: > Ok, so it's likely incomplete download. Definitely. It's a bit of a misfeature that the icon appears on the desktop before the download is complete. But I'd say there's no real issue here, besides my impatience/inattention. -- KBK ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make "fixing" it impossible before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is only used for empty lists. Which is not unlike the get() method of dicts. So may be the default should be None? ___ Python-Dev mailing list [email protected] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] can we stop pretending _PyTyple_Lookup is internal?
On 14-mrt-05, at 14:26, Michael Hudson wrote:
Armin Rigo <[EMAIL PROTECTED]> writes:
Hi Michael,
... _PyType_Lookup ...
There has been discussions about copy_reg.py and at least one other
place in
the standard library that needs this; it is an essential part of the
descriptor model of new-style classes. In my opinion it should be
made part
not only of the official C API but the Python one too, e.g. as a
method of
'type' instances: type(x).lookup('name')
Yes, this would be good too. The patch should be trivial; I guess a
little work is required to ensure b/w compat, but not very much
really.
It should IMHO be possible to override that method, the _PyType_Lookup
copy in
PyObjC that you mentioned earlier is slightly modified to deal with
Objective-C
categories.
Ronald
smime.p7s
Description: S/MIME cryptographic signature
___
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
