In my project I have to stick to Python 2.5 (Google App Engine). Somewhere in the application (actually a framework), I have to keep track which variables are defined and in which order they are defined, in other words I would like to intercept whenever an assignment operator is processed.
Using Python 3, I would define a metaclass M with a __prepare__
method that returns an intelligent dictionary that keeps track of when it is accessed. Then I just have to execute everything inside a class statement with metaclass M.
Is there any way to emulate this in Python 2.5?
EXAMPLE of what I would like to achieve
With the metaclass approach of Python 3, I could implement variables that work like references, for example M could be so that
# y is a callable
class C(metaclass=M):
x = ref(y)
x = 1
would be equivalent (up to the creation of C) with y(1)
, i.e. the first assignment to a variable in C's dictionary by a black-box ref
function creates this variable. Further assignments simply call the parameter of the ref function.
You can wrap the variables you populate your classes with with a wrapper that internally keeps a counter and assigns an increasing value. The wrapper may be subclassed for tagging or to add behaviour to the variables. You would use the variable value to order them and a regular Python 2 metaclass to intercept the class creation.
Django is one of the projects that uses this technique to remember the order in which members are defined on a model class. You can take a look at where the fields are created; it is then used in the implementation of the __cmp__
method to keep the fields in the order of creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With