Re: [Python-Dev] New syntax for 'dynamic' attribute access
On Fri, Feb 16, 2007 at 12:40:54PM +1300, Greg Ewing wrote: The quote is actually a camel is a *racehorse* designed by a committee. Camels are very good at surviving in the desert, but not so good at winning a horse race (not camel race). Which is the point of the saying. That changes the meaning, but... have you ever tried to ride a horse designed by a group of Clever Individuals loosely connected by email? ;) I am afraid of even thinking of its ugliness and speed. (-: I think a committee is better than nothing, and I believe CP4E has been dropped from the agenda. Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
I think a committee is better than nothing, and I believe CP4E has been dropped from the agenda. The general CP4E idea is part of the General Pythonic Ideal, whatever it may be :P -- EduardoOPadoan (eopadoan-altavix::com) Bookmarks: http://del.icio.us/edcrypt ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Oleg Broytmann schrieb: That changes the meaning, but... have you ever tried to ride a horse designed by a group of Clever Individuals loosely connected by email? ;) I am afraid of even thinking of its ugliness and speed. (-: I think a committee is better than nothing, and I believe CP4E has been dropped from the agenda. Ah, this passive voice again, and again the assumption that there is an agenda of python-dev. Regards, Martin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
* Ben North [EMAIL PROTECTED] [2007-02-11 23:45:05 +]: Dynamic attribute access is currently possible using the getattr and setattr builtins. The present PEP suggests a new syntax to make such access easier, allowing the coder for example to write x.('foo_%d' % n) += 1 z = y.('foo_%d' % n).('bar_%s' % s) instead of attr_name = 'foo_%d' % n setattr(x, attr_name, getattr(x, attr_name) + 1) z = getattr(getattr(y, 'foo_%d' % n), 'bar_%s' % s) Clipper (and other members of the xBase family) have something vaguely similar, and from working with that syntax, my feeling is that this is too subtle given the mixing of levels going on here (a literal name vs. an expression evaluating to a name). That is, it's too easy to not properly notice the presence / absence of the () and become confused between foo.bar and foo.(bar) or similar. (For the curious, the Clipper syntax is generally used in commands which are a kind of statement that is macro-evaluated; so, for example, something like this: USE clients will be transformed into something like the following expression: dbUseArea(clients) during the preprocessor pass, care of a builtin definition of USE; this function has the effect of opening a database file on disk for use. Now, in order to use the command syntax with a database name stored in a variable, one does something like the following: USE (dbName) which is transformed into something like: dbUseArea(dbname) with similar effects as before.) -- mithrandi, i Ainil en-Balandor, a faer Ambar signature.asc Description: Digital signature ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
A few of you have expressed concern about how would that look to a newbie. Being one, this is what I think: - The idea sounds good. Setattr and getattr seems both unpythonic and illegible. - please.(dont_torture) = me(with_dots,that_look,like.(function),calls). Ok, so the dot _is_ needed in order to indicate that we are talking about objects. But if I see something like spam.(eggs) , I would feel tempted to delete the dot thinking it's a typo. - Square brackets have enough overloading. - Braces feel good. I think they are the best choice of the ones proposed. Because spam{eggs} doesn't mean anything, then there would be no confusion with a typo in spam.{eggs} As someone said before, the problem is that it would limit braces for serving further purposes in the future. If the chances of requiring using braces in the next few versions seem low to you, I would say go for it. Sergio On 2/12/07, M.-A. Lemburg [EMAIL PROTECTED] wrote: On 2007-02-12 16:19, Georg Brandl wrote: Tim Delaney asked in particular: Have you checked if [the existing uses of getattr, where getattr in that scope is a function argument with default value the built-in getattr] are intended to bring the getattr name into local scope for fast lookup, or to force a binding to the builtin gettattr at compile time (two common (ab)uses of default arguments)? If they are, they would be better served by the new syntax. They're all in Lib/codecs.py, and are of the form: class StreamRecoder: def __getattr__(self, name, getattr=getattr): Inherit all other methods from the underlying stream. return getattr(self.stream, name) Without digging deeper into that code I'm afraid I can't say precisely what is going on. Since that is a special method and ought to have the signature __getattr__(self, name), I think it's safe to assume that that's meant as an optimization. I can confirm that: it's a case of fast-local-lookup optimization. You can add a -1 from me to the list as well: I don't think that dynamic lookups are common enough to warrant new syntax. Even if you do add a new syntax for this, using parenthesis is a poor choice IMHO as the resulting code looks too much like a function call (e.g. callable.(variable)). Other choices would be square brackets [], but these have the same problem as they are in use for indexing. The only brackets that are not yet overloaded in the context of applying them to an object are curly brackets, so callable.{variable} would cause enough raising eyebrows to not think of a typo. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 12 2007) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/sergio.correia%2Bpydev%40gmail.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On Thu, Feb 15, 2007 at 12:48:48AM +, Steve Holden wrote: Given that they say a camel is a horse designed by a committee Metaphors can go that far but not farther. And, BTW, camels are very suited for their environments... I am not afraid of committees for large tasks. Well, that has to be a small committee ruling by a cleverest ruler. require a single individual with good language design skills and the ability to veto features that were out of line with the design requirements. A lot like a BDFL, really. Of course, but I don't know if CP4E idea is still on his agenda and with what priority. Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Oleg Broytmann wrote: Given that they say a camel is a horse designed by a committee BTW, camels are very suited for their environments... The quote is actually a camel is a *racehorse* designed by a committee. Camels are very good at surviving in the desert, but not so good at winning a horse race (not camel race). Which is the point of the saying. -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Greg Ewing wrote: Oleg Broytmann wrote: Given that they say a camel is a horse designed by a committee BTW, camels are very suited for their environments... The quote is actually a camel is a *racehorse* designed by a committee. Camels are very good at surviving in the desert, but not so good at winning a horse race (not camel race). Which is the point of the saying. Speaking of which, have you ever seen a camel race? Those things go *fast* ... I think we're getting way too off-topic now ;) Tim Delaney ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Greg Ewing wrote: Oleg Broytmann wrote: Given that they say a camel is a horse designed by a committee BTW, camels are very suited for their environments... The quote is actually a camel is a *racehorse* designed by a committee. Camels are very good at surviving in the desert, but not so good at winning a horse race (not camel race). Which is the point of the saying. As far as I know Sir Alec Issigonis, the inventor of the Mini (the car, not the Mac Mini) said this, and he used horse, not racehorse. The point of the saying is that a camel has properties that are completely unnecessary in a horse, such as the ability to travel many days without water. He was saying that committees tend to over-specify and add redundant features rather than designing strictly for purpose. A bit like Python 3.0 ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Hi Michael, On Tue, Feb 13, 2007 at 11:55:46PM +, Michael Foord wrote: x = *('variable%d' % n) f(a, b, *('keyword%d' % n) = c) class *('33strangename'): pass def *(funcname)(x, y, *(argname), *args, **kwds): pass import *modname as mymodule Are you for these uses or mocking them ? Some of them look interesting... I don't actually have any strong opinion, I was just exploring all the places in the grammar that say NAME... Some of the above are definitely just absurd. In general I am failing to see much the point of syntax extensions, so I'll step out of this discussion again. Armin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Oleg Broytmann wrote: On Tue, Feb 13, 2007 at 10:10:37AM +, Steve Holden wrote: Python further away from the Computer Programming for Everyone arena and closer to the Systems Programming for Clever Individuals camp. That's because Python is being developed by Clever Individuals and not by Computer Programming for Everyone Committee. I agree that the developers are Clever Individuals. So clever, in fact, that they realise Python needs to be as approachable as possible, not a language for them alone. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On Wed, Feb 14, 2007 at 03:24:30PM +, Steve Holden wrote: Oleg Broytmann wrote: On Tue, Feb 13, 2007 at 10:10:37AM +, Steve Holden wrote: Python further away from the Computer Programming for Everyone arena and closer to the Systems Programming for Clever Individuals camp. That's because Python is being developed by Clever Individuals and not by Computer Programming for Everyone Committee. I agree that the developers are Clever Individuals. So clever, in fact, that they realise Python needs to be as approachable as possible, not a language for them alone. Anyway I don't believe it's possible to create a CP4E language without a CP4E Steering Committee, and I think such committee it Python land is... dormant at present... Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Oleg Broytmann wrote: On Wed, Feb 14, 2007 at 03:24:30PM +, Steve Holden wrote: Oleg Broytmann wrote: On Tue, Feb 13, 2007 at 10:10:37AM +, Steve Holden wrote: Python further away from the Computer Programming for Everyone arena and closer to the Systems Programming for Clever Individuals camp. That's because Python is being developed by Clever Individuals and not by Computer Programming for Everyone Committee. I agree that the developers are Clever Individuals. So clever, in fact, that they realise Python needs to be as approachable as possible, not a language for them alone. Anyway I don't believe it's possible to create a CP4E language without a CP4E Steering Committee, and I think such committee it Python land is... dormant at present... Given that they say a camel is a horse designed by a committee I think that language design by committee is very unlikely to produce something well suited to the needs of unsophisticated users. That would require a single individual with good language design skills and the ability to veto features that were out of line with the design requirements. A lot like a BDFL, really. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Martin v. Löwis schrieb: Ron Adam schrieb: I think it's gets a bit awkward in some situations. if bar-'__%s__' % attr -42: print 'Hello World' if bar.['__%s__' % attr] -42: print 'Hello World' To me it's easier to parse the second one visually. Ah, precedence. It definitly should be a bracketed form, or else people always wonder what the precedence is, and add parenthesis anyway just to be on the safe side. Indeed. BTW, which of these would be correct (a).[b] Yes. (you can write (a).b today) (a.)[b] No. (you can't write (a.)b today) a.[(b)] Yes. (you can write a[(b)] today) a.([b]) No. (you can't write a([b]) today) a . [ b ] Yes. (you can write a . b today) In short, I'd just add a new form to Grammar's trailer: trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' attrtrailer attrtrailer: '[' test ']' | NAME This should be consistent and unsurprising. and what is the semantics of a.[42] A TypeError, just as getattr(a, 42) would be. I think I like the .[] form better, that being a +0 now. Georg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Ben North wrote: Hi, A few days ago I posted to python-ideas with a suggestion for some new Python syntax, which would allow easier access to object attributes where the attribute name is known only at run-time. For example: setattr(self, method_name, getattr(self.metadata, method_name)) from Lib/distutils/dist.py could be rewritten self.(method_name) = self.metadata.(method_name) The new syntax would also be usable in augmented assignments, as in obj.(attr_name) += 1 There was some discussion on python-ideas, which I've linked to in the draft PEP below. In particular, Guido van Rossum wrote: I've thought of the same syntax. I think you should submit this to the PEP editor and argue on Python-dev for its inclusion in Python 2.6 -- there's no benefit that I see of waiting until 3.0. I don't like this. Just because an enhancement is syntactically permissible doesn't mean it's a good idea. This seems to me to take Python further away from the Computer Programming for Everyone arena and closer to the Systems Programming for Clever Individuals camp. so here I am. Does anybody have any opinions/suggestions, particularly on the open questions referred to in the draft PEP? To summarise these open questions: * The draft currently allows a two-argument form, to supply a default value if the object has no attribute of that name. This mimics the behaviour of the three-argument form of getattr, but looks a bit wrong: s = obj.(attr_name, 'default string') I agree that it looks odd, but perhaps the extra expressive power gained might be worth the oddness. It looks extremely odd. Since the opening parenthesis takes us into new syntactic territory the unimaginative use of the (already heavily overloaded) comma would sound the idea's death-knell. If we *have* to have this (and I agree with Greg that many uses cases for dynamic attribute access are invalid) then why not s = obj.(attr_name: 'default-string') I presume that the default value would in fact be an arbitrary expression? * The draft implementation (a sourceforge patch, linked to in the draft PEP) may have a general performance penalty of around 1%, although my initial measurements were quite noisy. Josiah Carlson thought this would not be too substantial, but he did suggest a couple of other implementation routes which could be explored. The general performance hit is offset by a speed gain of around 40% for attribute access using the new syntax over getattr etc. Is 1% too much for this feature? Yes. I believe it would decrease the sum total of Python's efficiency for a very marginal return in performance on a very marginal feature. It threatens to reduce Python's readability substantially, and readability is more important than efficiency. Expressive power is all very well as long as the expressiveness is comprehensible. This proposal makes the left parenthesis carry a larger burden than the introduction of generator expressions did, and it makes Python a more difficult language to understand. [provisional PEP snipped] If it's added in 2.6 I propose it should be deprecated in 2.7 and removed from 3.0 ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 13/02/07, Anthony Baxter [EMAIL PROTECTED] wrote: The killer problem with backticks (to pick the syntax that currently causes this problem the most) is with webpages and with printed books with code. Sure, everyone can pick a font for coding that they can read, but that's not the only way you read code. This is my issue with the foo.(bar) syntax. The period is far far too small and easy to miss. That's a good point, but I've been reading this thread in gmail (proportional font) and quite often using the wrong glasses (:-)) and I've found that the dot has never been that unreadable. Even where it isn't very visible, it introduces an extra bit of space, which makes me look again, and see what's going on. In practice, I find that distinguishing {}, [] and () is harder... Just a small data point. Paul. PS On the overall change, I'm +1, I don't have much opinion on exact syntax. And I'd second the comments that the way the PEP has been handled by Ben has been great - it's been very easy to follow what could have been a really messy thread. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 13/02/2007 7.39, Martin v. Löwis wrote: And again. Apparently, people favor hasattr over catching AttributeError. I'm not sure why this is - Because the code becomes longer, unless you want to mask other exceptions: name = 'http_error_%d' % errcode -if hasattr(self, name): -method = self.(name) +try: +method = self.(name) +except AttributeError: +pass +else: if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) -- Giovanni Bajo ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 13/02/2007 5.33, Maric Michaud wrote: I really dislikes the .[ or .( or .{ operators. Just on my mail editor the two expressions a.[b] and a,[b] are quite hard to differentiate while completely unrelated. I'll propose a new color for this bikeshed: a.[[b]] handlers = chain.get(kind, ()) for handler in handlers: func = handler.[[meth_name]] result = func(*args) if result is not None: return result Little heavy on the eye, but it seems that it's exactly what people want and can't find in the .[] syntax. -- Giovanni Bajo ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Taking a step back a bit... the basic issue is that we have an attribute namespace (compile time key determination) that we want to access in a dictionary style (runtime key determination). This is currently done by switching from syntactic access to the getattr/setattr/delattr builtin functions. Elsewhere in the thread, Calvin made the suggestion that, rather than introducing new syntax, this could instead be achieved with a wrapper class that automatically converted dict-style access into the appropriate calls to getattr/setattr/delattr. I've tried this out on Brett's urllib urllib2 examples below. (calling the new builtin attrview() to emphasise the fact that it retains a reference to the original instance). I don't consider it any uglier than the proposed syntax changes, and it provides a few other benefits: - the two-argument form is naturally available as the .get() method on the resulting dict-like object (e.g. attrview(obj).get(some_attr, None)) - hasattr() is naturally replaced by containment testing (e.g. some_attr in attrview(obj)) - keywords/builtins are easier to look up in the documentation than symbolic syntax With this approach, performance would be attained by arranging to create the view objects once, and then performing multiple dynamic attribute accesses using those view objects. First urllib.py example:: name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') self_d = attrview(self) if name in self_d: if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return self_d[name](url) else: return self_d[name](url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] Second urllib.py example:: name = 'http_error_%d' % errcode self_d = attrview(self) if name in self_d: method = self_d[name] if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) First urllib.py example:: if attr[:12] == '_Request__r_': name = attr[12:] get_name = 'get_' + name if get_name in attrview(Request): self_d = attrview(self) self_d[get_name]() return self_d[attr] raise AttributeError, attr Second urllib2.py example:: handlers = chain.get(kind, ()) for handler in handlers: func = attrview(handler)[meth_name] result = func(*args) if result is not None: return result Regards, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://www.boredomandlaziness.org ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Nick Coghlan wrote: I've tried this out on Brett's urllib urllib2 examples below. (calling the new builtin attrview() to emphasise the fact that it retains a reference to the original instance). Ooh, ooh! I wanna change my vote! +1 on attrview(), +0.25 on .[]. Maybe I haven't written enough Python, but I don't think you need this specialized form of accessing attributes very often. So I've shifted to the new syntax seems like overkill camp. Besides, once you've got the attrview() you can use all the existing dict syntax and it looks totally clean. The original example: setattr(self, method_name, getattr(self.metadata, method_name) which became in the new syntax: self.[method_name] = self.metadata.[method_name] would be: attrview(self)[method_name] = attrview(self.metadata)[method_name] And an attrview lets you use get() and the in operator. Plus, if you were performing a lot of operations on attributes all at one go, you'd cache it in a local and then it'd look even better. Perhaps object.__attrs__() returns a view on the object's attributes, and attrview() is simply a convenience function. /larry/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/13/07, Nick Coghlan [EMAIL PROTECTED] wrote: Taking a step back a bit... the basic issue is that we have an attribute namespace (compile time key determination) that we want to access in a dictionary style (runtime key determination). This is currently done by switching from syntactic access to the getattr/setattr/delattr builtin functions. Elsewhere in the thread, Calvin made the suggestion that, rather than introducing new syntax, this could instead be achieved with a wrapper class that automatically converted dict-style access into the appropriate calls to getattr/setattr/delattr. In other words, an object view analagous to what Py3K is doing with keys()/values()/items(). I've tried this out on Brett's urllib urllib2 examples below. (calling the new builtin attrview() to emphasise the fact that it retains a reference to the original instance). I don't consider it any uglier than the proposed syntax changes, and it provides a few other benefits: - the two-argument form is naturally available as the .get() method on the resulting dict-like object (e.g. attrview(obj).get(some_attr, None)) - hasattr() is naturally replaced by containment testing (e.g. some_attr in attrview(obj)) - keywords/builtins are easier to look up in the documentation than symbolic syntax Yeah, the generalization is really nice. It allows use to ditch getattr/setattr/hasattr all without losing the expressiveness of those built-ins. With this approach, performance would be attained by arranging to create the view objects once, and then performing multiple dynamic attribute accesses using those view objects. First urllib.py example:: name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') self_d = attrview(self) if name in self_d: if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return self_d[name](url) else: return self_d[name](url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] Second urllib.py example:: name = 'http_error_%d' % errcode self_d = attrview(self) if name in self_d: method = self_d[name] if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) First urllib.py example:: if attr[:12] == '_Request__r_': name = attr[12:] get_name = 'get_' + name if get_name in attrview(Request): self_d = attrview(self) self_d[get_name]() return self_d[attr] raise AttributeError, attr Second urllib2.py example:: handlers = chain.get(kind, ()) for handler in handlers: func = attrview(handler)[meth_name] result = func(*args) if result is not None: return result I also think it is just as clean as doing it any of the proposed ways:: getattr(self, name) self.[name] attrview(self)[name] So my vote is for Nick's object attribute view; +1. If we are going to do the view thing, let's go all the way! =) -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/13/07, Nick Coghlan [EMAIL PROTECTED] wrote: [snip] I've tried this out on Brett's urllib urllib2 examples below. (calling the new builtin attrview() to emphasise the fact that it retains a reference to the original instance). I don't consider it any uglier than the proposed syntax changes, and it provides a few other benefits: - the two-argument form is naturally available as the .get() method on the resulting dict-like object (e.g. attrview(obj).get(some_attr, None)) - hasattr() is naturally replaced by containment testing (e.g. some_attr in attrview(obj)) - keywords/builtins are easier to look up in the documentation than symbolic syntax With this approach, performance would be attained by arranging to create the view objects once, and then performing multiple dynamic attribute accesses using those view objects. This changes my vote: +1 on including attrview(), -1 on the syntax proposal. Collin Winter ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/13/07, Nick Coghlan [EMAIL PROTECTED] wrote: [snip] I've tried this out on Brett's urllib urllib2 examples below. (calling the new builtin attrview() to emphasise the fact that it retains a reference to the original instance). I don't consider it any uglier than the proposed syntax changes, and it provides a few other benefits: - the two-argument form is naturally available as the .get() method on the resulting dict-like object (e.g. attrview(obj).get(some_attr, None)) - hasattr() is naturally replaced by containment testing (e.g. some_attr in attrview(obj)) - keywords/builtins are easier to look up in the documentation than symbolic syntax With this approach, performance would be attained by arranging to create the view objects once, and then performing multiple dynamic attribute accesses using those view objects. On 2/13/07, Collin Winter [EMAIL PROTECTED] wrote: This changes my vote: +1 on including attrview(), -1 on the syntax proposal. Me too! I imagine that the addition of the proposed obj.[name] syntax to Python 2.6 would lead to more software that will not run on 2.5 and earlier versions. I don't think the benefits outweigh this backward incompatibility of new code. Therefore I'm -1 on including obj.[name] in Python 2.6. For Python 3000, I think it would be alright. With attrview(obj)[name] it would be possible to provide a fallback implementation in the same module for pre-2.6 users, so +1 for that. Johann C. Rocholl ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Hi, On Mon, Feb 12, 2007 at 12:38:27AM -0700, Neil Toronto wrote: obj.*str_expression x = *('variable%d' % n) f(a, b, *('keyword%d' % n) = c) class *('33strangename'): pass def *(funcname)(x, y, *(argname), *args, **kwds): pass import *modname as mymodule Sorry for the noise, Armin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Armin Rigo wrote: Hi, On Mon, Feb 12, 2007 at 12:38:27AM -0700, Neil Toronto wrote: obj.*str_expression x = *('variable%d' % n) f(a, b, *('keyword%d' % n) = c) class *('33strangename'): pass def *(funcname)(x, y, *(argname), *args, **kwds): pass import *modname as mymodule Are you for these uses or mocking them ? Some of them look interesting... FWIW, at Resolver (75k lines of IronPython code currently) we use getattr / setattr almost as many as 8 times. (I was very surprised at how low that was.) That said, when I explained the proposal to two of my colleagues both of them were *very* happy with the obj.[name] suggestion. Michael Foord Sorry for the noise, Armin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/fuzzyman%40voidspace.org.uk ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Martin v. Löwis wrote: Apparently, people favor hasattr over catching AttributeError. I'm not sure why this is - I would probably rewrite them all to deal with AttributeError if I use the new syntax in the first place. Actually, I prefer using getattr with a default value over either of those, wherever possible. AttributeError can be raised by too many things for me to feel comfortable about catching it. This suggests that any proposed getattr syntax should include a way of specifying a default value. I'm still -1 on the basic idea, though, on the grounds of YAGNIOE (You Aren't Going to Need It Often Enough). -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Martin v. Löwis wrote: BTW, which of these would be correct My thoughts would be (a).[b] Okay (a.)[b] Not okay a.[(b)] Okay a.([b]) Not okay a . [ b ]Okay and what is the semantics of a.[42] The same as getattr(a, 42), which depends on a's __getattr__ implementation. -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On Feb 13, 2007, at 7:24 PM, Greg Ewing wrote: I'm still -1 on the basic idea, though, on the grounds of YAGNIOE (You Aren't Going to Need It Often Enough). I can't really add much more than what's already be stated, but I echo Greg's sentiment. - -Barry -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.5 (Darwin) iQCVAwUBRdJaynEjvBPtnXfVAQJHuQP7B7FlA5wO28dEW62q3VSOr7iUm/6FLZ/6 hoXq47S1F/Yre0bl9p1C2bOCAXeBNXoQC55oPw4a4XUC3C2G/Pf3TJnlOZ0u1M7y 5Ug8MbDxf8SvHl3efZSOjvx2S8OPv0m11teP+d9l11upXz7ASAVlwYZhKRMum6/s ECxTGOKH2tc= =ZSIW -END PGP SIGNATURE- ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Martin v. Löwis wrote: OTOH, you can't write x + = 2 or a = 2 * * 4 Although oddly enough you *can* write a[. . .] I guess whoever added the ellipsis couldn't be bothered defining a new token for it. It's something of an arbitrary choice, but to me it just seems that the dot and bracket *should* be separare tokens, perhaps because I would be thinking of the [x] as a special kind of argument to the dot operator, rather than there being a funny new operator called .[. -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
This seems to be the overwhelming feedback at this point, so I'm withdrawing my support for the proposal. I hope that Ben can write up a PEP and mark it rejected, to summarize the discussion; it's been a useful lesson. Occasinoally, negative results are worth publishing! On 2/13/07, Barry Warsaw [EMAIL PROTECTED] wrote: On Feb 13, 2007, at 7:24 PM, Greg Ewing wrote: I'm still -1 on the basic idea, though, on the grounds of YAGNIOE (You Aren't Going to Need It Often Enough). I can't really add much more than what's already be stated, but I echo Greg's sentiment. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/13/07, Greg Ewing [EMAIL PROTECTED] wrote: Martin v. Löwis wrote: OTOH, you can't write x + = 2 or a = 2 * * 4 Although oddly enough you *can* write a[. . .] I guess whoever added the ellipsis couldn't be bothered defining a new token for it. But if we ever turn it into a single token (which we just may for Py3k) don't complain if your code breaks. It's something of an arbitrary choice, but to me it just seems that the dot and bracket *should* be separare tokens, perhaps because I would be thinking of the [x] as a special kind of argument to the dot operator, rather than there being a funny new operator called .[. Yes, that's how I was thinking of it. But it's all moot now. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Guido van Rossum wrote: But if we ever turn it into a single token (which we just may for Py3k) don't complain if your code breaks. I won't. I always treat it as a single token anyway, unless I'm entering an obfuscated python competition. :-) -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 12-feb-2007, at 0:45, Ben North wrote: self.(method_name) = self.metadata.(method_name) I like the functionality, but I don't like the syntax, to me it looks too much like a method call. To me self.[method_name] = self.metadata.[method_name] looks better: what we're doing here is more like dictionary lookup than calling functions. -- Jack Jansen, [EMAIL PROTECTED], http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Terry Reedy wrote: Need: Runtime attributes are a fairly frequent 'How?' question on c.l.p. That's true, but how many of those are due to an actual need for runtime attributes, as opposed to someone trying to transplant idioms from another language that would be better served by a dict? In my experience, the amount of code which truly needs to use getattr is extremely small. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | Carpe post meridiem! | Christchurch, New Zealand | (I'm not a morning person.) | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Georg Brandl wrote: For the speed argument -- there were quite a few proposals to take builtins as constants under certain conditions, in which case getattr() usage could be optimized just as well as new syntax. Even more aggressively, the compiler could recognise it and make a direct call to the __getattr__ method, or maybe even have a new opcode for doing that. In other words, special syntax doesn't necessarily have to look like special syntax. :-) -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
[Jack Jansen] I like the functionality, but I don't like the syntax, to me it looks too much like a method call. To me self.[method_name] = self.metadata.[method_name] looks better: what we're doing here is more like dictionary lookup than calling functions. I also like the functionality. Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name I like the arrow syntax because is the lookup process can be more involved than a simple dictionary lookup (perhaps traveling up to base classes). IOW, getattr(a,n) is not always the same as a.__dict__[n]. The a.__getattribute__(n) process can be more complex than that and a bracketed dictionary-like syntax would misleadingly mask the lookup process. Raymond ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/11/07, Ben North [EMAIL PROTECTED] wrote: Hi, A few days ago I posted to python-ideas with a suggestion for some new Python syntax, which would allow easier access to object attributes where the attribute name is known only at run-time. For example: setattr(self, method_name, getattr(self.metadata, method_name)) from Lib/distutils/dist.py could be rewritten self.(method_name) = self.metadata.(method_name) The new syntax would also be usable in augmented assignments, as in obj.(attr_name) += 1 -1 from me. It does not solve a common problem, therefore it does not deserve a special syntax. Moreover, the existing syntax may be longer to type but is far more readable. -- Gustavo J. A. M. Carneiro The universe is always one step beyond logic. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] New syntax for 'dynamic' attribute access
Thanks for the comments so far on this. First, on the general idea: Neil Toronto: I like it. [...] obj.(attr_name) += 1 Even nicer; much, much better than the current spelling. Brett Cannon: +0 on the one-item version. Anthony Baxter: -1 from me. Collin Winter: I like the general idea [...] I'm +0 on the idea Jack Jansen: I like the functionality, Raymond Hettinger: I also like the functionality. Generally gently positive, with the exception of Anthony Baxter's -1, which I understand to be motivated by concerns about newcomers to the syntax: Someone coming across this syntax for the first time will not have any hints as to what it means - and worse, it looks like a syntax error to me. This was echoed by Collin Winter: Also, like Anthony Baxter said, someone coming across this for the first time will think it's a syntax error, allusions to MATLAB and assembly indirection syntax not withstanding. [...] -1 on the means. I think the argument someone who hasn't come across it before won't know what it is could be applied to any new syntax, for instance the new with statement, or going further back in time, the introduction of Booleans, semantics of __slots__, the extended print syntax, the list comprehension syntax, the augmented assignment syntax, etc. Some of these were perhaps more transparent than others, but for instance with needs a bit of study to fully understand what's going on. I would argue that the newness itself is not sufficient reason to reject this. Also, I think it's a good thing that it looks like a syntax error --- it *is* currently a syntax error. A newcomer will be alerted to the fact that something new is going on and will know to go and find out about it. I am happy to write a paragraph for the what's new release notes, and/or new section(s) for the documentation describing the new syntax. On the two-argument form, feeling was generally pretty negative, with a few -1s thrown in. I propose to cut this piece out of the PEP, leaving just the one-argument form. If a default value is required, the coder can still use the three-argument form of getattr. To be clear (and I'll put this in the PEP), I'm *not* suggesting that python loses getattr, setattr, or delattr. On the syntax: Brett Cannon: It just makes it look like too much of a function call at that point to me Collin Winter: the syntax looks like dirt on my monitor. The period is too easy to lose visually and without it, there's nothing to distinguish this from a function call. Jack Jansen: I don't like the syntax, to me it looks too much like a method call. (Some of the initial comments in python-ideas were along these lines too.) My personal opinion is that obj.(foo) is distinct enough from obj(foo) to not cause confusion, but perhaps in a proportional font it is less clear. Some people made concrete suggestions as to what syntax could be used instead: Jack Jansen: To me self.[method_name] = self.metadata.[method_name] looks better: what we're doing here is more like dictionary lookup than calling functions. In the same way, though, would this be viewed as too similar to normal dictionary/list indexing? Raymond Hettinger: Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name One thing which comes to mind about this one is that, for C/C++ programmers, the difference between obj.memberand obj-member is the interpretation of the thing on the *left* of the dot or arrow, whereas the PEP is discussing a new interpretation of the thing on the *right* of the dot. One idea mentioned in the PEP is to bring {}s into service here, but I think the dot should be kept to keep it looking like an attribute access. What would the reaction be to obj.{member} instead? Braces are already used to construct dictionaries, so this has some of the right connotations. It could not be confused with either a function call or a dictionary lookup/list indexing. (Nobody had any comments on the potential 1% performance hit --- is this because it's too early to worry about implementation details?) Thanks, Ben. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] New syntax for 'dynamic' attribute access
Apologies: I overlooked a couple of replies in my summary earlier. Tim Delaney and Terry Reedy both responded in positive terms to the one-argument form and its syntax, and in negative terms to the two-argument form. Also, I missed the fact that Neil Toronto had made the same point as me when he said: I'm not sure the looks like a syntax error argument holds much weight, because any new syntax is likely to be a syntax error until the syntax is changed. :) he also suggested: obj.*str_expression but I'm a bit uneasy about this, although the similarity with C's dereferencing is in its favour. Also, '*' in python is already used for and the rest arguments in function calls. Anthony Baxter cooled off a bit on the idea too: after thinking about it a bit, I'm still not convinced this is something that needs shorthand syntax Maybe not, but for the cases where you do want to do dynamic attribute access, I think there is a win in readability from nested getattr and/or setattr calls. Georg Brandl: -1 here too. I fear that this gets too indistinguishable from normal calling syntax, I think, from the context, that this is -1 on the syntax rather than the idea as a whole, but I could have misread Georg's message. Possibly a -0 on the idea? Greg Ewing: In my experience, the amount of code which truly needs to use getattr is extremely small. Another -0? Gustavo Carneiro: -1 from me. It does not solve a common problem, therefore it does not deserve a special syntax. It's not *that* uncommon, judging by the c.600 uses in the existing library code. Moreover, the existing syntax may be longer to type but is far more readable. I disagree, although I can see that there might be a small time during which one is getting familiar with the new syntax. Others have voiced the opinion that it's a readability win. Tim Delaney asked in particular: Have you checked if [the existing uses of getattr, where getattr in that scope is a function argument with default value the built-in getattr] are intended to bring the getattr name into local scope for fast lookup, or to force a binding to the builtin gettattr at compile time (two common (ab)uses of default arguments)? If they are, they would be better served by the new syntax. They're all in Lib/codecs.py, and are of the form: class StreamRecoder: def __getattr__(self, name, getattr=getattr): Inherit all other methods from the underlying stream. return getattr(self.stream, name) Without digging deeper into that code I'm afraid I can't say precisely what is going on. Ben. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Ben North wrote: Jack Jansen: To me self.[method_name] = self.metadata.[method_name] looks better: what we're doing here is more like dictionary lookup than calling functions. In the same way, though, would this be viewed as too similar to normal dictionary/list indexing? I think that's its strength; it's pleasantly symmetric to using [] on a dict: dictattribute behavior [] .[] pulls out named thing, throws exception on failure, no default, is an lvalue .get() .getattr()pulls out named thing, returns default value on error (specifiable as second argument), not an lvalue List comprehensions look like funny lists, generator expressions look like funny expressions, I see no reason why attribute dereferencing shouldn't look like funny dict dereferencing. +1. What would the reaction be to obj.{member} instead? Braces are already used to construct dictionaries, so this has some of the right connotations. -0.5. You're not constructing anything, you're looking up something. For the record, I'm also -1 on the two-argument form--this isn't a function call. /larry/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2007-02-12 16:19, Georg Brandl wrote: Tim Delaney asked in particular: Have you checked if [the existing uses of getattr, where getattr in that scope is a function argument with default value the built-in getattr] are intended to bring the getattr name into local scope for fast lookup, or to force a binding to the builtin gettattr at compile time (two common (ab)uses of default arguments)? If they are, they would be better served by the new syntax. They're all in Lib/codecs.py, and are of the form: class StreamRecoder: def __getattr__(self, name, getattr=getattr): Inherit all other methods from the underlying stream. return getattr(self.stream, name) Without digging deeper into that code I'm afraid I can't say precisely what is going on. Since that is a special method and ought to have the signature __getattr__(self, name), I think it's safe to assume that that's meant as an optimization. I can confirm that: it's a case of fast-local-lookup optimization. You can add a -1 from me to the list as well: I don't think that dynamic lookups are common enough to warrant new syntax. Even if you do add a new syntax for this, using parenthesis is a poor choice IMHO as the resulting code looks too much like a function call (e.g. callable.(variable)). Other choices would be square brackets [], but these have the same problem as they are in use for indexing. The only brackets that are not yet overloaded in the context of applying them to an object are curly brackets, so callable.{variable} would cause enough raising eyebrows to not think of a typo. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 12 2007) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
My perspective: - There's a lot of support for the basic idea, and only a few naysayers, so let's keep looking for a syntax that works. - There's near-universal dislike for the two-arg form, so let's drop that part of the proposal. - I can't recall that x.[y] has been proposed yet, but thinking about it, that actually makes more sense than x.(y). (In fact, in JavaScript you can write x[y] to the same effect. I wouldn't discount the JS example; JS is probably closer to Python than almost any other language currently in existence except for Boo, and JS has successfully borrowed from Python.) - I'm not too concerned by the '.' being such a small character with this new proposal. x[y] is a lot less common than x(y), so you'll look twice when you think you see x[y] and it doesn't make sense, and then you'll notice it's really x.[y], which you either know or don't, and in the latter case you'll be looking it up or asking around. PS Thanks to Ben for excellent summaries of the discussion so far! -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On Mon, 12 Feb 2007 18:50:35 +1100, you wrote: Yes and no. My point is that it's extremely similar to existing syntax. (Worse yet, it looks the same but for what's possibly the smallest and hardest-to-see character in any character set) foo(baz) vs foo.(baz) is... not good. To me (as a newbee to the language) I only see possible confusion if one gives 'static' looking examples like: x.(foo) += 1 which does indeed look a bit like a function call. However when giving more 'dynamic' looking examples like: x.('foo_%d' % n) += 1 I don't get confused at all and intuitively recognize the intention immediately. In this example I consider the parenthesis 'grouping operators' (which would not be the case when square brackets would have been used) So, +1 for the idea from me, since the main intention is to use it in a 'dynamic' context, and there it would improve readability. All IMHO as a newbee of course :) Ton. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
[Raymond Hettinger] Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name [Ben North] One thing which comes to mind about this one is that, for C/C++ programmers, the difference between obj.memberand obj-member is the interpretation of the thing on the *left* of the dot or arrow, whereas the PEP is discussing a new interpretation of the thing on the *right* of the dot. Try not to get hung-up on meanings from other languages. Any simple syntax will have associations in other languages. It is more important that we don't create a syntax which already has strong associations in Python (i.e. curly braces, dots, and square brackets). Those syntaxes would make the language harder to mentally parse. I would like to give the - syntax a chance as is it simple and it is provides a nice visual distinction between closely related concepts: a.name --getattr(a, 'name') a-name --getattr(a, name) Raymond ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Guido van Rossum schrieb: PS Thanks to Ben for excellent summaries of the discussion so far! I'd like to second this. This is how PEPs ought to work. Regards, Martin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/12/07, Raymond Hettinger [EMAIL PROTECTED] wrote: [Jack Jansen] I like the functionality, but I don't like the syntax, to me it looks too much like a method call. To me self.[method_name] = self.metadata.[method_name] looks better: what we're doing here is more like dictionary lookup than calling functions. I also like the functionality. Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name I like the arrow syntax because is the lookup process can be more involved than a simple dictionary lookup (perhaps traveling up to base classes). IOW, getattr(a,n) is not always the same as a.__dict__[n]. The a.__getattribute__(n) process can be more complex than that and a bracketed dictionary-like syntax would misleadingly mask the lookup process. I actually kind of like that. The connection to pointer indirection meshes well with the idea of indirectly figuring out what attribute to access at runtime. -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/12/07, Raymond Hettinger [EMAIL PROTECTED] wrote: [Raymond Hettinger] Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name [Ben North] One thing which comes to mind about this one is that, for C/C++ programmers, the difference between obj.memberand obj-member is the interpretation of the thing on the *left* of the dot or arrow, whereas the PEP is discussing a new interpretation of the thing on the *right* of the dot. Try not to get hung-up on meanings from other languages. Any simple syntax will have associations in other languages. An example of where Python has been willing in the past to hijack syntax and give it a tweaked meaning is decorators compared to Java annotations. It is more important that we don't create a syntax which already has strong associations in Python (i.e. curly braces, dots, and square brackets). Those syntaxes would make the language harder to mentally parse. I think this is a nice argument against using square brackets as well. Currently square brackets are used for getting an item from a container (__getitem__) or generating one (list comprehensions). While using the .[] syntax does connect with the container idea if you want to treat an object as a container and its attributes as its items, I don't think the connection is that strong. Guido said he would be much more willing to look twice at a use of brackets for a dot, but that seems to require mental backtracking to me. If I am skimming some source and I see square brackets, right now I know that either something has defined __getitem__ and is probably a dict or list, or it is a listcomp if it contains 'for'. But with this I would now have to stop and look for that dot which could be lost in the noise. I think people are calling the syntax dirt because you have two pieces of syntax ('.' and '[') that are a single character. And on top of that they are extremely thin (which sucks for non-monospaced fonts). We don't have issues with dots these days since there is usually several characters of information specifying the meaning of what the dot is modified by the dot. But in this case there is very little visual queue for that. I would like to give the - syntax a chance as is it simple and it is provides a nice visual distinction between closely related concepts: a.name --getattr(a, 'name') a-name --getattr(a, name) Yeah, I am definitely liking this one more. It's making the ``.[name]`` or ``.(name)`` look more like dirt on Tim's monitor to me. -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/12/07, Brett Cannon [EMAIL PROTECTED] wrote: On 2/12/07, Raymond Hettinger [EMAIL PROTECTED] wrote: [Jack Jansen] I like the functionality, but I don't like the syntax, to me it looks too much like a method call. To me self.[method_name] = self.metadata.[method_name] looks better: what we're doing here is more like dictionary lookup than calling functions. I also like the functionality. Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name I like the arrow syntax because is the lookup process can be more involved than a simple dictionary lookup (perhaps traveling up to base classes). IOW, getattr(a,n) is not always the same as a.__dict__[n]. The a.__getattribute__(n) process can be more complex than that and a bracketed dictionary-like syntax would misleadingly mask the lookup process. I actually kind of like that. The connection to pointer indirection meshes well with the idea of indirectly figuring out what attribute to access at runtime. There's a connection, but I'd say it's the wrong one. In C, x-y dereferences x, while in Python, x-y would dereference y. That's just begging for trouble. Collin Winter ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
FWIW, I'm strongly -1 on the - notation. As a C programmer it's got too many neurons committed to it. I recommend that you do some experiments with the readability of the .[...] notation, e.g. write a program that randomly generates x.[foo] and x[foo], and see how fast you can spot the difference. I bet that you won't have any trouble. --Guido On 2/12/07, Brett Cannon [EMAIL PROTECTED] wrote: On 2/12/07, Raymond Hettinger [EMAIL PROTECTED] wrote: [Raymond Hettinger] Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name [Ben North] One thing which comes to mind about this one is that, for C/C++ programmers, the difference between obj.memberand obj-member is the interpretation of the thing on the *left* of the dot or arrow, whereas the PEP is discussing a new interpretation of the thing on the *right* of the dot. Try not to get hung-up on meanings from other languages. Any simple syntax will have associations in other languages. An example of where Python has been willing in the past to hijack syntax and give it a tweaked meaning is decorators compared to Java annotations. It is more important that we don't create a syntax which already has strong associations in Python (i.e. curly braces, dots, and square brackets). Those syntaxes would make the language harder to mentally parse. I think this is a nice argument against using square brackets as well. Currently square brackets are used for getting an item from a container (__getitem__) or generating one (list comprehensions). While using the .[] syntax does connect with the container idea if you want to treat an object as a container and its attributes as its items, I don't think the connection is that strong. Guido said he would be much more willing to look twice at a use of brackets for a dot, but that seems to require mental backtracking to me. If I am skimming some source and I see square brackets, right now I know that either something has defined __getitem__ and is probably a dict or list, or it is a listcomp if it contains 'for'. But with this I would now have to stop and look for that dot which could be lost in the noise. I think people are calling the syntax dirt because you have two pieces of syntax ('.' and '[') that are a single character. And on top of that they are extremely thin (which sucks for non-monospaced fonts). We don't have issues with dots these days since there is usually several characters of information specifying the meaning of what the dot is modified by the dot. But in this case there is very little visual queue for that. I would like to give the - syntax a chance as is it simple and it is provides a nice visual distinction between closely related concepts: a.name --getattr(a, 'name') a-name --getattr(a, name) Yeah, I am definitely liking this one more. It's making the ``.[name]`` or ``.(name)`` look more like dirt on Tim's monitor to me. -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Is even more syntactic sugar really what Python really needs? -- mvh Björn ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] New syntax for 'dynamic' attribute access
Guido van Rossum wrote: - There's near-universal dislike for the two-arg form, so let's drop that part of the proposal. This is a strong consensus, definitely, so we can conclude that this point has been decided. I will remove it from the PEP. Guido also wrote: - There's a lot of support for the basic idea, and only a few naysayers, so let's keep looking for a syntax that works. If we can take that as a decision, then the various proposals for the syntax break down as follows. By raw numbers, the most popular choice is self.(method_name) = self.metadata.(method_name) but many of the I like that messages were in the context of the idea as a whole, so can't really be counted as explicit votes for obj.(foo) as such. Next, and Guido's preferred choice, is self.[method_name] = self.metadata.[method_name] (I haven't been following long enough to know whether Guido likes it overrides everything else (the D of BDFL), or is more of a casting vote in the event of a tie.) With regard to the potential overlookability of the dot, Guido says: I recommend that you do some experiments with the readability of the .[...] notation, e.g. write a program that randomly generates x.[foo] and x[foo], and see how fast you can spot the difference. I bet that you won't have any trouble. I agree --- just as it's important to have a font that makes it easy to distinguish I from l and 1, 0 from O, ( from {, etc., I would say it's important to program using a font which makes it easy to tell whether there's a . in your code. I can imagine that a proportional font where . might be a single pixel wouldn't help, though. (Gently wandering off-topic, but: do people use proportional fonts for coding? Doesn't it cause general awkwardness for indentation, especially relevant for python?) Also mentioned was self.{method_name} = self.metadata.{method_name} which could not be confused either with function call or indexing but perhaps would preclude braces from any potential future use. Exploring other ideas, the arrow notation self-method_name = self.metadata-method_name has support, and is clearly different, but I personally would be misled to think, from the meaning in C, that it ought to be the left-hand operand which is dereferenced somehow. Guido has the same opinion, and is strongly -1 on this. The star form has the dereference meaning from C, and is certainly visually distinctive: self.*method_name = self.metadata.*method_name and explicit parentheses could be put in as a syntax requirement, or by individual coder preference, or for more complex attribute calculations: self.*(method_name) = self.metadata.*(method_name) self.*('foo_%d' % n) = self.metadata.*('foo_%d' % n) The downside is that it could be considered visually distinctive to the point of being line noise. Could we cut down the choice to self.[method_name] = self.metadata.[method_name] if the danger of overlooking the dot were deemed small enough, or self.*(method_name) = self.metadata.*(method_name) if the consensus was that something more noticeable was needed? (Or there's always the late arrival In C, x-y dereferences x, while in Python, x-y would dereference y. Then the syntax should obviously be x-y. [insert in-Soviet-Russia-variables-dereference-you joke here] from Benji York.) Ben. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Ben North wrote: Generally gently positive, with the exception of Anthony Baxter's -1, which I understand to be motivated by concerns about newcomers to the syntax The more I think about it, the more I'm leaning towards -1 as well. Adding syntax is a very big step, and it needs a very solid reason to jusify it. I don't see this filling a use case that's anywhere near common enough to reach that threshold. -- Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/12/07, BJörn Lindqvist [EMAIL PROTECTED] wrote: Is even more syntactic sugar really what Python really needs? Yes, I need my fix!!! my 2 cents: I'm +1 on either the '.(name)' or '.[name]' syntax. I'm leaning more towards the parentheses though. I don't really buy into the argument that people will confuse it for a function call. That seems like more of an argument against the dot operator in general than the new syntax. I'm -1 on the '-' syntax. It just doesn't look very clean to me. -Farshid ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
2007/2/12, Benji York [EMAIL PROTECTED]: Collin Winter wrote: There's a connection, but I'd say it's the wrong one. In C, x-y dereferences x, while in Python, x-y would dereference y. That's just begging for trouble. Then the syntax should obviously be x-y. delurk Someone with OCaml background could confuse that with an assignment evil_grin/ /delurk -- Marek Baczyński ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/12/07, Guido van Rossum [EMAIL PROTECTED] wrote: FWIW, I'm strongly -1 on the - notation. As a C programmer it's got too many neurons committed to it. I recommend that you do some experiments with the readability of the .[...] notation, e.g. write a program that randomly generates x.[foo] and x[foo], and see how fast you can spot the difference. I bet that you won't have any trouble. OK, so real-world examples. First, ``foo.(name)``, from urllib.py:: name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return self.(name)(url) else: return self.(name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] and also:: name = 'http_error_%d' % errcode if hasattr(self, name): method = self.(name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) And here is urllib2.py for ``.[]`` (used different files so you wouldn't just remember where the change was):: if attr[:12] == '_Request__r_': name = attr[12:] if hasattr(Request, 'get_' + name): self.['get_' + name]() return self.[attr] raise AttributeError, attr and:: handlers = chain.get(kind, ()) for handler in handlers: func = handler.[meth_name] result = func(*args) if result is not None: return result Neither version jumps out at me strongly, although between the two the ``.[]`` version shows up the best. But that might also be because of the lower noise when used in a call. -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Benji York wrote: Collin Winter wrote: On 2/12/07, Brett Cannon [EMAIL PROTECTED] wrote: I actually kind of like that. The connection to pointer indirection meshes well with the idea of indirectly figuring out what attribute to access at runtime. There's a connection, but I'd say it's the wrong one. In C, x-y dereferences x, while in Python, x-y would dereference y. That's just begging for trouble. Then the syntax should obviously be x-y. I'd actually gone through this process myself, and concluded that I wouldn't be happy with either. x-y: is currently invalid syntax, but has *very* strong connotations from C. Whilst I'm happy to consider things that deviate from other languages' use, this one is just too strong. x-y is currently valid syntax, and gives (to mee) the wrong impression that y is that thing that's going to be modified. Of all the proposals I've seen, I think I like x.{y} best. The use of {} has connotations of interpolation and they're the only braces that currently don't have meaning as x{} (and probably never will). I do worry that giving syntax to getattr/setattr/delattr will encourage the use of dynamic attributes, when they are a fairly advanced feature. OTOH, when you're using advanced features, you want the code to be as readable as possible, and I think this will improve readability over using getattr/setattr/delattr. So I think I've changed to +0.5. Tim Delaney ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On Tuesday 13 February 2007 10:10, Ben North wrote: (Gently wandering off-topic, but: do people use proportional fonts for coding? Doesn't it cause general awkwardness for indentation, especially relevant for python?) The killer problem with backticks (to pick the syntax that currently causes this problem the most) is with webpages and with printed books with code. Sure, everyone can pick a font for coding that they can read, but that's not the only way you read code. This is my issue with the foo.(bar) syntax. The period is far far too small and easy to miss. -- Anthony Baxter [EMAIL PROTECTED] It's never too late to have a happy childhood. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Brett Cannon wrote: On 2/12/07, Guido van Rossum [EMAIL PROTECTED] wrote: I recommend that you do some experiments with the readability of the .[...] notation, e.g. write a program that randomly generates x.[foo] and x[foo], and see how fast you can spot the difference. I bet that you won't have any trouble. OK, so real-world examples. First, ``foo.(name)``, from urllib.py:: [snip] Neither version jumps out at me strongly, although between the two the ``.[]`` version shows up the best. But that might also be because of the lower noise when used in a call. -Brett After seeing a real-world example of the notation, I'm not a fan. Like Brett, of the two I find .[] to be the most readable. I do in fact immediately associate an identifier next to () with being a function call, regardless of the dot. The [] immediately associates me with a type of dereferencing action which is more appropriate for the context. The danger here is that foo.bar and baz.(bar) use bar in drastically different ways and it is not made obvious enough. baz.[bar] gets you closer because we are used to seeing bar as a variable containing a key (as opposed to foo.bar where 'bar' is in fact the key). At the risk of needing flame retardant, I would propose the use of something more visually jarring. The first thing that came to mind was something like [EMAIL PROTECTED]. The only usage of the @ symbol I can recall is in Ruby where it is used instead of self. for attribute access, which is in the right ballpark for what we mean here and the brackets differentiate it still. To borrow the urllib2.py example: if attr[:12] == '_Request__r_': name = attr[12:] if hasattr(Request, 'get_' + name): [EMAIL PROTECTED]'get_' + name]() return [EMAIL PROTECTED] raise AttributeError, attr -Scott -- Scott Dial [EMAIL PROTECTED] [EMAIL PROTECTED] ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Oh, now I am definitely in favor of .[]! I read it in gmail in FireFox which uses a small variable-pitch font whose dot is a single pixel. The .() example was hard to find; the .[] jumped out immediately. (When do you ever see self[anything]?) On 2/12/07, Brett Cannon [EMAIL PROTECTED] wrote: On 2/12/07, Guido van Rossum [EMAIL PROTECTED] wrote: FWIW, I'm strongly -1 on the - notation. As a C programmer it's got too many neurons committed to it. I recommend that you do some experiments with the readability of the .[...] notation, e.g. write a program that randomly generates x.[foo] and x[foo], and see how fast you can spot the difference. I bet that you won't have any trouble. OK, so real-world examples. First, ``foo.(name)``, from urllib.py:: name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return self.(name)(url) else: return self.(name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] and also:: name = 'http_error_%d' % errcode if hasattr(self, name): method = self.(name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) And here is urllib2.py for ``.[]`` (used different files so you wouldn't just remember where the change was):: if attr[:12] == '_Request__r_': name = attr[12:] if hasattr(Request, 'get_' + name): self.['get_' + name]() return self.[attr] raise AttributeError, attr and:: handlers = chain.get(kind, ()) for handler in handlers: func = handler.[meth_name] result = func(*args) if result is not None: return result Neither version jumps out at me strongly, although between the two the ``.[]`` version shows up the best. But that might also be because of the lower noise when used in a call. -Brett -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Raymond Hettinger wrote: Rather than munge existing syntaxes, an altogether new one would be more clear: self-name = self.metadata-name My problem with this is that it isn't a name. It should grammatically be a test (i.e. it can take on the expression any function argument could take). How do you spell getattr(self, 'req_' + state) with that arrow? You need some kind of grouping delimiters to make this operator be a syntax benefit otherwise you didn't shorten anything. -Scott -- Scott Dial [EMAIL PROTECTED] [EMAIL PROTECTED] ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On Feb 12, 2007, at 7:32 PM, Guido van Rossum wrote: Oh, now I am definitely in favor of .[]! I read it in gmail in FireFox which uses a small variable-pitch font whose dot is a single pixel. The .() example was hard to find; the .[] jumped out immediately. (When do you ever see self[anything]?) Raymond's - suggestion was nice. - -Barry -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.5 (Darwin) iQCVAwUBRdEIB3EjvBPtnXfVAQLENQP+KlLGE0rldGbOdpeMdsZ6dX7ga9Fb2mZR wkOIEYJW6H8n6OyzawPgkvQWpuJzUlC+5A42gxYUdkC4pTxWqzJQ6i6csoVOD+ya 1vztCUavDTG9HznH4tX6L2bRJI2fhBdfMxkNCnSpmRaW1SOpOgutLMQv5ZxmLzHU xjkaqp9ogPY= =gu74 -END PGP SIGNATURE- ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
A few of you have expressed concern about how would that look to a newbie. Being one, this is what I think: (again, newbie alert) - The idea sounds good. Setattr and getattr seem kinda unpythonic and difficult to read. - please.(dont_torture) = me(with_dots,that_look,like.(function),calls). Ok, so the dot _is_ needed in order to indicate that we are talking about objects. But if I see something like spam.(eggs) , I would feel tempted to delete the dot thinking it's a typo. Besides, the parenthesis make the dot even harder to read. - x-y feels like assignment. I even recall that in Mathematica it IS some kind of assignment. Besides, it lacks the dot that tells me this is an object. - Square brackets have a lot of overloading but are not so bad. - Braces feel good. I think they are the best choice of the ones proposed. Because spam{eggs} doesn't mean anything, then there would be no confusion with a typo in spam.{eggs} --Sergio On 2/12/07, M.-A. Lemburg [EMAIL PROTECTED] wrote: On 2007-02-12 16:19, Georg Brandl wrote: Tim Delaney asked in particular: Have you checked if [the existing uses of getattr, where getattr in that scope is a function argument with default value the built-in getattr] are intended to bring the getattr name into local scope for fast lookup, or to force a binding to the builtin gettattr at compile time (two common (ab)uses of default arguments)? If they are, they would be better served by the new syntax. They're all in Lib/codecs.py, and are of the form: class StreamRecoder: def __getattr__(self, name, getattr=getattr): Inherit all other methods from the underlying stream. return getattr(self.stream, name) Without digging deeper into that code I'm afraid I can't say precisely what is going on. Since that is a special method and ought to have the signature __getattr__(self, name), I think it's safe to assume that that's meant as an optimization. I can confirm that: it's a case of fast-local-lookup optimization. You can add a -1 from me to the list as well: I don't think that dynamic lookups are common enough to warrant new syntax. Even if you do add a new syntax for this, using parenthesis is a poor choice IMHO as the resulting code looks too much like a function call (e.g. callable.(variable)). Other choices would be square brackets [], but these have the same problem as they are in use for indexing. The only brackets that are not yet overloaded in the context of applying them to an object are curly brackets, so callable.{variable} would cause enough raising eyebrows to not think of a typo. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 12 2007) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/sergio.correia%2Bpydev%40gmail.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Barry Warsaw wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On Feb 12, 2007, at 7:32 PM, Guido van Rossum wrote: Oh, now I am definitely in favor of .[]! I read it in gmail in FireFox which uses a small variable-pitch font whose dot is a single pixel. The .() example was hard to find; the .[] jumped out immediately. (When do you ever see self[anything]?) Raymond's - suggestion was nice. I think it's gets a bit awkward in some situations. if bar-'__%s__' % attr -42: print 'Hello World' if bar.['__%s__' % attr] -42: print 'Hello World' To me it's easier to parse the second one visually. Ron ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Le mardi 13 février 2007 01:36, Barry Warsaw a écrit : On Feb 12, 2007, at 7:32 PM, Guido van Rossum wrote: Oh, now I am definitely in favor of .[]! I read it in gmail in FireFox which uses a small variable-pitch font whose dot is a single pixel. The .() example was hard to find; the .[] jumped out immediately. (When do you ever see self[anything]?) Raymond's - suggestion was nice. I really dislikes the .[ or .( or .{ operators. Just on my mail editor the two expressions a.[b] and a,[b] are quite hard to differentiate while completely unrelated. Why did the brace syntax wasn't even discussed ? Seems clean to me. obj{expr} can be read as given obj as a namespace, retrieve the name resulting by expr in obj and enclosing namespaces (supers). We can even use slice-like syntax for further improvements : obj{expr:default} obj{expr:default:type_} something like getattr(super(type_, obj), expr, default), or even obj{expr::} for getattr(super(obj.__class__, obj), expr) and, why not, even obj{:} for super(obj.__class__, obj), regards, ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
M.-A. Lemburg [EMAIL PROTECTED] wrote: You can add a -1 from me to the list as well: I don't think that dynamic lookups are common enough to warrant new syntax. I agree. Also, I think the special syntax may make them too inviting to new programmers, who haven't figured out that usually there are better ways of doing things. Even if you do add a new syntax for this, using parenthesis is a poor choice IMHO as the resulting code looks too much like a function call (e.g. callable.(variable)). Yes. The .[] notation looks much better, IMO. Neil ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/12/07, Maric Michaud [EMAIL PROTECTED] wrote: Le mardi 13 février 2007 01:36, Barry Warsaw a écrit: On Feb 12, 2007, at 7:32 PM, Guido van Rossum wrote: Oh, now I am definitely in favor of .[]! I read it in gmail in FireFox which uses a small variable-pitch font whose dot is a single pixel. The .() example was hard to find; the .[] jumped out immediately. (When do you ever see self[anything]?) Raymond's - suggestion was nice. I really dislikes the .[ or .( or .{ operators. Just on my mail editor the two expressions a.[b] and a,[b] are quite hard to differentiate while completely unrelated. Yeah, so are 1.2 and 1,2. This is why the style guide (PEP 8) insists on a space after a comma but not after a period. Why did the brace syntax wasn't even discussed ? Seems clean to me. Because they are arbitrary -- if x{y} or x.{y} would be acceptable, why not x.y or x.|y| or x./y/? Or indeed why not [EMAIL PROTECTED] (Not that I'm in favor of that. :-) That x.[y] and x.(y) resemble x[y] and x(y) is an *advantage* of the proposed new notation, not a disadvantage; the new operator is semantically closer to x[y] than to x(y) so x.[y] makes sense. obj{expr} can be read as given obj as a namespace, retrieve the name resulting by expr in obj and enclosing namespaces (supers). Yeah, it can just as well be read as call obj with 2**expr as argument. Also, your reference to enclosing namespaces and supers is misplaced -- this should map to the existing __getattr__ operation, which can have many different semantics depending on the type of obj. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Brett Cannon schrieb: name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else: return self.open_unknown(fullurl, data) try: if data is None: return self.(name)(url) else: return self.(name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2] Also notice that this leaves a hasattr call in, as there is no replacement proposed for that. name = 'http_error_%d' % errcode if hasattr(self, name): method = self.(name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers) Likewise. if attr[:12] == '_Request__r_': name = attr[12:] if hasattr(Request, 'get_' + name): self.['get_' + name]() return self.[attr] raise AttributeError, attr And again. Apparently, people favor hasattr over catching AttributeError. I'm not sure why this is - I would probably rewrite them all to deal with AttributeError if I use the new syntax in the first place. Regards, Martin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Ron Adam schrieb: I think it's gets a bit awkward in some situations. if bar-'__%s__' % attr -42: print 'Hello World' if bar.['__%s__' % attr] -42: print 'Hello World' To me it's easier to parse the second one visually. Ah, precedence. It definitly should be a bracketed form, or else people always wonder what the precedence is, and add parenthesis anyway just to be on the safe side. BTW, which of these would be correct (a).[b] (a.)[b] a.[(b)] a.([b]) a . [ b ] and what is the semantics of a.[42] Regards, Martin ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] New syntax for 'dynamic' attribute access
Hi, A few days ago I posted to python-ideas with a suggestion for some new Python syntax, which would allow easier access to object attributes where the attribute name is known only at run-time. For example: setattr(self, method_name, getattr(self.metadata, method_name)) from Lib/distutils/dist.py could be rewritten self.(method_name) = self.metadata.(method_name) The new syntax would also be usable in augmented assignments, as in obj.(attr_name) += 1 There was some discussion on python-ideas, which I've linked to in the draft PEP below. In particular, Guido van Rossum wrote: I've thought of the same syntax. I think you should submit this to the PEP editor and argue on Python-dev for its inclusion in Python 2.6 -- there's no benefit that I see of waiting until 3.0. so here I am. Does anybody have any opinions/suggestions, particularly on the open questions referred to in the draft PEP? To summarise these open questions: * The draft currently allows a two-argument form, to supply a default value if the object has no attribute of that name. This mimics the behaviour of the three-argument form of getattr, but looks a bit wrong: s = obj.(attr_name, 'default string') I agree that it looks odd, but perhaps the extra expressive power gained might be worth the oddness. * The draft implementation (a sourceforge patch, linked to in the draft PEP) may have a general performance penalty of around 1%, although my initial measurements were quite noisy. Josiah Carlson thought this would not be too substantial, but he did suggest a couple of other implementation routes which could be explored. The general performance hit is offset by a speed gain of around 40% for attribute access using the new syntax over getattr etc. Is 1% too much for this feature? Ben. - - - - 8 - - - - PEP: 363 [PROVISIONAL NUMBER] Title: Syntax For Dynamic Attribute Access Version: $Revision$ Last-Modified: $Date$ Author: Ben North ben at redfrontdoor.org Status: Draft Type: Standards Track Content-Type: text/plain Created: 29-Jan-2007 Post-History: Abstract Dynamic attribute access is currently possible using the getattr and setattr builtins. The present PEP suggests a new syntax to make such access easier, allowing the coder for example to write x.('foo_%d' % n) += 1 z = y.('foo_%d' % n).('bar_%s' % s) instead of attr_name = 'foo_%d' % n setattr(x, attr_name, getattr(x, attr_name) + 1) z = getattr(getattr(y, 'foo_%d' % n), 'bar_%s' % s) Note (I wrote this patch mostly to advance my own understanding of and experiment with the python language, but I've written it up in the style of a PEP in case it might be a useful idea.) Rationale Dictionary access and indexing both have a friendly invocation syntax: instead of x.__getitem__(12) the coder can write x[12]. This also allows the use of subscripted elements in an augmented assignment, as in x[12] += 1. The present proposal brings this ease-of-use to dynamic attribute access too. Attribute access is currently possible in two ways: * When the attribute name is known at code-writing time, the .NAME trailer can be used, as in x.foo = 42 y.bar += 100 * When the attribute name is computed dynamically at run-time, the getattr and setattr builtins must be used: x = getattr(y, 'foo_%d' % n) setattr(z, 'bar_%s' % s, 99) The getattr builtin also allows the coder to specify a default value to be returned in the event that the object does not have an attribute of the given name: x = getattr(y, 'foo_%d' % n, 0) This PEP describes a new syntax for dynamic attribute access --- x.(expr) --- with examples given in the Abstract above. The new syntax also allows the provision of a default value in the get case, as in: x = y.('foo_%d' % n, None) This 2-argument form of dynamic attribute access is not permitted as the target of an (augmented or normal) assignment. Also, this part of the new syntax was not as well received [6] in initial discussions on python-ideas, and I agree that it does not fit so cleanly. I'm happy to prepare a revised PEP/patch without the 2-argument form if the consensus is that this would be preferred. Finally, the new syntax can be used with the del statement, as in del x.(attr_name) Impact On Existing Code The proposed new syntax is not currently valid, so no existing well-formed programs have their meaning altered by this proposal. Across all *.py files in the 2.5 distribution, there are around 600 uses of getattr, setattr or delattr. They break down as follows (figures have some room for error because they were arrived at by partially-manual inspection): c.300 uses of plain getattr(x, attr_name), which could be
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Ben North wrote: c.5 uses which would have to stay as getattr because they are calls of a variable named getattr whose default value is the builtin getattr; Have you checked if these are intended to bring the getattr name into local scope for fast lookup, or to force a binding to the builtin gettattr at compile time (two common (ab)uses of default arguments)? If they are, they would be better served by the new syntax. Overall, +1 on obj.(attr_name) -0 on obj.(attr_name, default_value) Tim Delaney ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
On 2/11/07, Ben North [EMAIL PROTECTED] wrote: [SNIP] * The draft currently allows a two-argument form, to supply a default value if the object has no attribute of that name. This mimics the behaviour of the three-argument form of getattr, but looks a bit wrong: s = obj.(attr_name, 'default string') I agree that it looks odd, but perhaps the extra expressive power gained might be worth the oddness. I don't think it is. getattr can just be kept around if need be in order to support this use case. It just makes it look like too much of a function call at that point to me, especially if someone ends up writing some expression that is so long that they put in a newline between the two values: s = obj.(attr_name, 'default_string') So -1 on the two-item version, +0 on the one-item version. -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
I have to say that I'm not that impressed by either the 1-arg or 2-arg versions. Someone coming across this syntax for the first time will not have any hints as to what it means - and worse, it looks like a syntax error to me. -1 from me. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
I like the general idea, but the syntax looks like dirt on my monitor. The period is too easy to lose visually and without it, there's nothing to distinguish this from a function call. Also, like Anthony Baxter said, someone coming across this for the first time will think it's a syntax error, allusions to MATLAB and assembly indirection syntax not withstanding. Ignoring the syntax, I'm -1 on the 2-argument form, especially since it can only be used in an expression context; getattr() can be kept around for this. I'm +0 on the idea, -1 on the means. Collin Winter ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Anthony Baxter wrote: I have to say that I'm not that impressed by either the 1-arg or 2-arg versions. Someone coming across this syntax for the first time will not have any hints as to what it means - and worse, it looks like a syntax error to me. -1 from me. I'm not sure the looks like a syntax error argument holds much weight, because any new syntax is likely to be a syntax error until the syntax is changed. :) No hints is a decent argument against it, though. Parenthesis are already used for tuples, function calls, precedence, and generator comprehensions. The more something gets overloaded, the more ambiguous it looks. How about obj.*str_expression instead? * is pretty common in the C family of languages as a dereferencing operator. Neil ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] New syntax for 'dynamic' attribute access
Collin Winter schrieb: I like the general idea, but the syntax looks like dirt on my monitor. The period is too easy to lose visually and without it, there's nothing to distinguish this from a function call. Also, like Anthony Baxter said, someone coming across this for the first time will think it's a syntax error, allusions to MATLAB and assembly indirection syntax not withstanding. Ignoring the syntax, I'm -1 on the 2-argument form, especially since it can only be used in an expression context; getattr() can be kept around for this. I'm +0 on the idea, -1 on the means. -1 here too. I fear that this gets too indistinguishable from normal calling syntax, leading to confusion. (Of course, one could propose other syntax, such as obj-(attr) or whatnot, but I doubt an ideal and Pythonic syntax can be found here...) To me, dynamic attribute access is something special, and it justifies a different way of doing it, namely getattr and setattr. For the speed argument -- there were quite a few proposals to take builtins as constants under certain conditions, in which case getattr() usage could be optimized just as well as new syntax. Georg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com