Python name is undefined, but evaluates to true. How?

I have python code like this:

try:
    bob = bob_module.Bob('alpha')
except Exception as e:
    print 'Alpha mode failed for bob: '  + str(e) + ').'

try:
    if bob:
        bob.add('Beta')
    else:
        bob = bob_module.Bob('Beta')
except Exception as e:
    print 'Beta mode failed for bob: ' + str(e) + ').'

      

When this code was running in Alpha mode it failed, for obvious reason (communication with the alpha server failed). However, the beta mode failed because the name "bob" is not defined. "

Surely, if the name is bob

not defined, then it if bob

equates to false, we insert into the clause else

and run the constructor bob

, assigning the result to the variable bob

?

I can't debug this because the bug that caused the Alpha mode to fail was temporary and is now gone, but I would like to understand this for two reasons: intellectual curiosity and to make my code reliable in case of alpha mode running again doesn't work.

+3


source to share


2 answers


When you do:

bob = bob_module.Bob('alpha')

      

Python will not reach the destination phase (by scheduling a return from a failed function call) - it will skip directly to the catching exception phase.

Since bob remains undefined when you try to use it later in the statement:

if bob:

      

Python doesn't know what bob

, let alone whether it will evaluate with True

or False

so it will take out another error.



If you want to bob

be predefined regardless of the result of the first function, just assign it None

before the function call so that Python knows bob

is None

and can therefore correctly evaluate it in the if statement no matter what happened before.

UPDATE . If you really don't want to define your own in advance bob

, you can check for its existence with something like:

if "bob" in globals():  # replace globals() with locals() for the current scope

      

or check if it exists and if the value exists True

:

if globals().get("bob", None):  # replace globals() with locals() for the current scope

      

+2


source


Of course, if the name bob is undefined, then if bob evaluates to false

Not. If bob

not defined, it is an error to try to use it.



Place bob = None

at the beginning of the file to make sure it is defined in all codes.

+6


source







All Articles