3 ms·
> For what’s it worth, Python 3 gets it right: > ... > Also, would you expect hasattr() to raise that error? Not really no. I would expect hasattr() to just an
by alkonaut 11y ago
> For what’s it worth, Python 3 gets it right:
> ...
> Also, would you expect hasattr() to raise that error?
Not really no. I would expect hasattr() to just answer whether the attribute exists, and getattr() to actually invoke it. If "hasattr" actually invokes the attribute and just checks for a non-empty value returned, is it even needed? It would completely surprise me, coming from a language with static types + reflection, that a query for a types attributes (mere existence) would invoke them.
- icebraining 11y agoThing is, what does it mean for a property to "exist" in a dynamic language like Python? E.g. class P(object): def __getattr_(self, attrname): return "hello" >>> p = P() >>> print p.foo hello Does "p" have an attribute "foo"?
- alkonaut 11y agoThat is the snag isn't it. It's really difficult to provide any meaningful "reflection" without having proper static types. So in your example you could say "yes, because it gets a value when called" or "no, because it isn't explicitly declared". Since python is dynamic, the "hasattr" method really just means "does_invoking_this_attribute_return_something", which is very much not reflection. It would maybe be useful with getting only the explicitly defined attributes (say e.g. if you wanted to convert an object to an xsd schema). Your __getattr__ based attribute would not show up in that list obviously.