Set a flag on the function or a global?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Jun 16 05:15:52 EDT 2015
On Tuesday 16 June 2015 10:24, Ron Adam wrote:
> Another way is to make it an object with a __call__ method.
>
> The the attribute can be accessed from both outside and inside dependably.
That's what functions are, objects with a __call__ method:
py> (lambda: None).__call__
<method-wrapper '__call__' of function object at 0xb7301a04>
One slight disadvantage is that functions don't take a "self" parameter by
default, which means they have to refer to themselves by name:
def spam():
print spam.attr
Here's a fun hack:
py> from types import MethodType
py> def physician(func):
... # As in, "Physician, Know Thyself" :-)
... return MethodType(func, func)
...
py> @physician
... def spam(this, n):
... return this.food * n
...
py> spam.__func__.food = "spam-and-eggs "
py> spam(3)
'spam-and-eggs spam-and-eggs spam-and-eggs '
Alas, you cannot write directly to the method object itself :-(
--
Steve
More information about the Python-list
mailing list