Domanda

In Python is it possible to avoid a variable (pre-) declaration to avoid a NameError: name 'c' is not defined:

a=5
if a==7:
    c=10
if c: print c

On a last line if c: simply verifies if variable 'c' is not None. What can be used to check if 'c' variable even exist (or was pre-declared)?

È stato utile?

Soluzione

Sure, assign None to it first:

a = 5
c = None
if a == 7:
    c = 10
if c:
    print c

None tests as False in a boolean context, so if c: still works as written.

You could also catch the NameError exception:

try:
    print c
except NameError:
    pass

or use the globals() and locals() functions:

if 'c' in locals():
    # in a function

if 'c' in globals():
    # outside a function

but that's just plain ugly and unnecessary.

Altri suggerimenti

You could catch the exception.

a = 5
if a == 7:
    c = 10
try:
    print c
except NameError:
    pass

You can use locals to check if the variable is in the local scope:

>>> c = 1
>>> locals()
{'__doc__': None, 'c': 1, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__package__': None}
>>> 'c' in locals()
True
>>>

You may also be interested in globals.

It is not clear why you would need a variable under certain circumstances and not others, but the simplest thing is to move the print into the scope c is assigned in:

if a == 7:
    c = 10
    print(c)

or to remove the variable entirely:

if a == 7:
    print(10)

In python3 and despite Martijn thinking that it is ugly:
If you know the variable is a global:

if globals().get('abc'): print (True)

if you know that it is local:

if locals().get('abc'): print (True)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top