Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize variables to None/Undefined and compare to other variables in Python?

Tags:

python

Basically I have some variables that I don't want to preinitialize:

originalTime = None
recentTime = None
postTime = None

def DoSomething ( ) :
    if originalTime == None or (postTime - recentTime).seconds > 5 :
        ...

I get compile error on the if:

UnboundLocalError: local variable 'originalTime' referenced before assignment

As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.

Any ideas?

like image 752
Joan Venge Avatar asked Apr 28 '09 23:04

Joan Venge


2 Answers

I need to correct Jarret Hardie, and since I don't have enough rep to comment.

The global scope is not an issue. Python will automatically look up variable names in enclosing scopes. The only issue is when you want to change the value. If you simply redefine the variable, Python will create a new local variable, unless you use the global keyword. So

originalTime = None

def doSomething():
  if originalTime:
    print "originalTime is not None and does not evaluate to False"
  else:
    print "originalTime is None or evaluates to False"

def doSomethingElse():
  originalTime = True

def doSomethingCompletelyDifferent()
  global originalTime
  originalTime = True

doSomething()
doSomethingElse()
doSomething()
doSomethingCompletelyDifferent()
doSomething()

Should output:

originalTime is None or evaluates to False
originalTime is None or evaluates to False
originalTime is not None and does not evaluate to False

I second his warning that this is bad design.

like image 55
AFoglia Avatar answered Oct 10 '22 01:10

AFoglia


Your code should have worked, I'm guessing that it's inside a function but originalTime is defined somewhere else. Also it's a bit better to say originalTime is None if that's what you really want or even better, not originalTime.

like image 44
Scott Kirkwood Avatar answered Oct 10 '22 02:10

Scott Kirkwood