Sunday, November 11, 2012

static in Python - 1

My friend Dave (also my ex-TA) always points me to interesting posts on StackOverflow after I introduced it to him. He likes helping others to succeed whenever possible. I admire him a lot. He's a great mentor.

He was my instructor for my Computer Organization lab a year ago. Last night he linked me to What and where are the stack and heap?. That was his response. In our class, Dave went over scope and lifetime of static and automatic variables. I still remember most of the details. But he got very excited when I said Python programmers don't really need to worry about static allocation because for such a high-level language Python programmers just pass things around.

He wrote an example to illustrate how static variable(s) was used in Python. Later tonight he went over how he used this in his Database homework. He was writing a class for functional dependency and multi-value dependency. He subclass FD to make MVD. He wanted to show A -> B and A ->-> B. But instead of hardcoding the string -> and ->-> he thought of static variable.

Idea:

class FD:
	_ARROW_STRING = "->"

class MVD(FD):
        _ARROW_STRING = "->->"  # or even just * 2 I think that's fine too

I think that's the idea. When using static variable, all instances of FD and MVD will refer to the same _ARROW_STRING which saves memory. Imagine we have 10000 instances of FD. That's a lot of saving.

Sometimes, I as a Python programmer, overlook the old school C++ stuff because they look boring and confusing. But sometimes, a small trick like that will help. Global variables are okay too, but if we want to encapsulate it into the class, we might as well just make it as a static member variable. I mean, global variables are also statically allocated. It doesn't really make any difference in general.

In the next post I will mention more about statics in Python.... sometimes bugs me right now.

No comments:

Post a Comment