How do I put off attribute access in Python?
Let’s assume we have:
def foo():
...
class Bar:
...
bar = Bar()
Is it possible to implement Bar so that any time bar is accessed, a value returned by the callback foo() would be provided?
bar name already exists in the context. That’s why it’s access semantics should be preserved (it cannot be a callable, turning bar into a property of a class, using SomeClass.bar instead of bar also won’t work). I need to keep everything as-is, but change the program so that bar would refer to on-the-fly generated data by foo().
UPD: Thanks all for your answers, from which it seems impossible to do this type of thing in Python. I’m gonna find a workaround.
Thanks for the clarification!
This just can’t work! A variable is a variable in most languages, not a function-call. You can do much in Python, but you just can’t do that.
The reason is, that you have always some intrinsic language rules. One rule in Python is, that variables are variables. When you read a variable (not modifying it or anything else) you can rely, that it will be the same in the next code-line.
Monkeypatching it to be a function call would just change this rule.
What you want, could only be done by a still more dynamic language. Something like a macro-processing system or a language that do not have variables but something like labels that can be attached to anything. But this would also make compiler-creation for it much more difficult — hence fully dynamic. The compiler would have to take all coding in the program into account.