Question

On http://effbot.org/zone/python-getattr.htm it states that

Python’s getattr function is used to fetch an attribute from an object, using 
a string object instead of an identifier to identify the
attribute. In other words, the following two statements are
equivalent:

    value = obj.attribute
    value = getattr(obj, "attribute")

What is confuses me is that I have a module with a class with dynamic classmethod generation. I know that the generation works because calling __dict__ returns

 >>> errors.__dict__
mappingproxy({'__module__': 'utils.errors', '__weakref__': 
<attribute '__weakref__' of 'errors' objects>,'404': <classmethod object at 
0x7fe547c23190>, '500': <classmethod object at 0x7fe547c23210>, '403': 
<classmethod object at 0x7fe547c23110>, '400': <classmethod object at 
0x7fe547c23090>})

What is confusing me is the face that getattr works, while calling the attribute directly does not

>>> errors.404("asdf")
  File "<console>", line 1
    errors.404("asdf")
             ^
SyntaxError: invalid syntax
>>> getattr(errors,'404')("asdf")
{'error': 'Page Not Found', 'code': 404, 'message': 'asdf'}
Was it helpful?

Solution

Identifiers starting with a number are not valid identifiers (ref).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top