[Python-Dev] New syntax for 'dynamic' attribute access
Brett Cannon
brett at python.org
Tue Feb 13 00:47:26 CET 2007
On 2/12/07, Guido van Rossum <guido at python.org> 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
More information about the Python-Dev
mailing list