[Python-Dev] New syntax for 'dynamic' attribute access (original) (raw)

"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.openunknownproxy(proxy, fullurl, data) else: return self.openunknown(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.excinfo()[2]

Also notice that this leaves a hasattr call in, as there is no replacement proposed for that.

name = 'httperror%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.httperrordefault(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