[Python-Dev] New syntax for 'dynamic' attribute access
"Martin v. Löwis"
martin at v.loewis.de
Tue Feb 13 07:39:18 CET 2007
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
More information about the Python-Dev
mailing list