Wednesday, June 16, 2010

[Py] Add new attributes as static variables

One problem I have met when coding with Python is that there seems no static variables to apply. A straightforward approach is to use the global variables, but it is not such a safe way.

Several days ago, when I was writing my nth version of my low-pass/high-pass filtering functions, I found a nice method to keep some values of certain variables which would be used in recursive steps. This method is to create new attributes of the called function, and the created attributes could be used as static variables.

The original information has been given in Ref. and I would like to repeat it again but with my own understanding. The function which have to keep some local variables as static ones could be as follows.

1. def foo(argv):
2. if not "your_static_var" in dir(foo):
3. foo.your_static_var = certain initial values
4. do something with foo.your_static_var
5. return foo.your_static_var

In line 2, we check all the attributes of foo() by the built-in function dir(). If foo() is called for the first time, we could create new attributes with initializations as shown in line 3. I think this is the most brilliant part of the method.

Next time when you need ``local'' static variables for certain functions, this approach may help.

Ref: (see the post by Cameron Laird)
Python - Static Variables in Python?

No comments:

Post a Comment