views:

61

answers:

2

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.

A: 

One place to start is by looking at PEP-3115 and reading about the "current" behavior, e.g. the behavior that was current before Python 3 was implemented.

Tim McNamara
+1  A: 

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.

piro
@piro: Thanks a lot for pointing out the technique that is being used by Django. This would solve my problem with the relative order of the assignments. What it doesn't solve, however, is to keep track of the variables being assigned. I will edit my question to make this point clear in a moment.
Marc