is it possible to access the python function object attributes from within the function scope?
e.g. let’s have
def f():
return SOMETHING
f._x = "foo"
f() # -> "foo"
now, what SOMETHING has to be, if we want to have the _x attribute content “foo” returned? if it’s even possible (simply)
thanks
UPDATE:
i’d like the following work also:
g = f
del f
g() # -> "foo"
UPDATE 2:
Statement that it is not possible (if it is the case), and why, is more satisfying than providing a way how to fake it e.g. with a different object than a function
Solution
Make one of the function’s default arguments be a reference to the function itself.
Example usage:
Explanation
The original poster wanted a solution that does not require a global name lookup. The simple solution
performs a lookup of the global variable
fon each call, which does not meet the requirements. Iffis deleted, then the function fails. The more complicatedinspectproposal fails in the same way.What we want is to perform early binding and store the bound reference within the object itself. The following is conceptually what we are doing:
In the above,
selfis a local variable, so no global lookup is performed. However, we can’t write the code as-is, becausefis not yet defined when we try to bind the default value ofselfto it. Instead, we set the default value afterfis defined.Decorator
Here’s a simple decorator to do this for you. Note that the
selfargument must come last, unlike methods, whereselfcomes first. This also means that you must give a default value if any of your other arguments take a default value.Example: