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 ?
I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)
then I can define
Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.