getattr nested attributes
Paul Boddie
paul at boddie.org.uk
Fri Aug 15 09:42:26 EDT 2008
On 15 Aug, 10:35, Gregor Horvath <g... at gregor-horvath.com> wrote:
>
> <type 'exceptions.AttributeError'>: type object 'B' has no attribute
> 'a.test'
You have to realise that attributes can have names beyond those
supported by the usual attribute access syntax. For example:
class C: pass
setattr(C, "x.y", 123)
getattr(C, "x.y") # gives 123
setattr(C, "class $$$", 456)
getattr(C, "class $$$") # gives 456
Note that there's no way of using the object.name syntax to access
these attributes, although some proposals have been made to allow it
in some fashion. What you should conclude from this is that the name
argument to setattr and getattr is just a name, not an expression,
even if you can construct names which look like expressions or other
syntactically meaningful fragments of code.
> Documentation says B.a.test and getattr(B, "a.test") should be equivalent.
>
> http://docs.python.org/lib/built-in-funcs.html
No, the documentation says that the name must be "the name of one of
the object's attributes", not an expression fragment that if combined
with the name of the object and evaluated would yield an attribute
from some object or other reachable via the original object.
Paul
More information about the Python-list
mailing list