Not many are aware of this feature, but Python's functions (and methods) can have attributes. Behold:
>>> def foo(x):
... pass
...
>>> foo.score = 10
>>> dir(foo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score']
>>> foo.score
10
>>> foo.score += 1
>>> foo.score
11
What are the possible uses and abuses of this feature in Python ? One good use I'm aware of is PLY's usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?
type
(i.e. to parse string to some other type), and as it's one I'm anticipating reusing, I gave it ahelp
attribute, containing a string which is a sensible default for anadd_argument()
'shelp
parameter in cases where this type is used. Very niche, but definitely handy. – Ashe