1

I am trying to set a static variable inside a function. Essentially, I want this variable to be false initially. After the first time this function is called, I want the variable to be set to true.

I currently have the following:

class LKTracker(object):
 def track_points(self,width,height):
 if not hasattr(track_points, "gotInitialFeatures"):
 track_points.gotInitialFeatures = None
 if not track_points.gotInitialFeatures:
 #do some stuff
 track_points.gotInitialFeatures = True

With this code, I keep receiving the following error:

NameError: global name 'track_points' is not defined

Anyone know what is happening here?

asked Oct 25, 2013 at 9:16
0

2 Answers 2

6

In a global function, you can refer directly to the function object by looking up the name.

This does not work in a method; you'd have to look the method up on the class instead:

LKTracker.track_points

This still won't do what you want, however, because you'd get a unbound method object at that moment:

>>> LKTracker.track_points
<unbound method LKTracker.track_points>

Method objects are created on demand (because functions are descriptors), and creating an attribute on a method object is futile; they generally only live for a short while.

You'd need to access the function instead:

>>> LKTracker.track_points.__func__
<function track_points at 0x103e7c500>

but you can do the same thing on self:

self.track_points.__func__

Now you can add a attribute:

track_points = self.track_points.__func__
if not hasattr(track_points, "gotInitialFeatures"):
 track_points.gotInitialFeatures = None
if not track_points.gotInitialFeatures:
 #do some stuff
track_points.gotInitialFeatures = True

But it would be much easier to just store that attribute on the class instead:

if not hasattr(LKTracker, 'gotInitialFeatures'):
answered Oct 25, 2013 at 9:24

1 Comment

Thank you Martijn. I think I got it :)
1

You shall init static variable before call a function.

def static_var(varname, value):
 def decorate(func):
 setattr(func, varname, value)
 return func
 return decorate

and now you can:

@static_var("gotInitialFeatures", False)
def track_points(self, width, height):
 ...
answered Oct 25, 2013 at 9:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.