How to check if a variable was defined in Python?

7

Is there any way to check whether or not a variable was defined in Python?

    
asked by anonymous 10.02.2015 / 17:56

3 answers

12

If the variable is local, this is basically it:

if 'variavel' in locals():

If you want to know if it exists among the global ones:

if 'variavel' in globals():

And finally if it is a member of some object:

if hasattr(objeto, 'variavel'):

These are the direct ways to verify the existence of the variable. There are other ways you can help discover existence. QMechanic73 discovered one and posted in its response that the dir() function can list variables in scope or attributes of available objects. Any other ways do not verify existence. There are ways that will generate an exception, which is not technically checking for existence, but taking actions after trying to access a non-existent variable.

    
10.02.2015 / 18:00
2

Another alternative way is dir() function:

  

Without arguments, returns a list of names of the current scope. With argument, returns a list of valid attributes for this object.

See the examples below:

# Exemplo 1
class Pessoa:
    def __init__(self, nome, peso):
        self.nome = nome
        self.peso = peso

pessoa = Pessoa('Wallace', 50)

if 'nome' in dir(pessoa):
    # "nome" existe na classe "Pessoa"
    pass        
if 'peso' in dir(pessoa):
    # "peso" existe na classe "Pessoa"
    pass

# Exemplo 2
nome = 'Wallace'
peso = 50

if 'nome' in dir():
    # "nome" existe nesse escopo
    pass
if 'peso' in dir():
    # "peso" existe nesse escopo
    pass

Another way is to handle the exception NameError , it is generated when a name local or global is not found.

def foo():
    try:
        nome = 'Wallace'
        nome =+ idade  # A variável idade não está definida
    except NameError:  # Captura a exceção
        idade = '50'   # Define a variável

    return nome + idade   

print (foo())
    
10.02.2015 / 21:25
0

Another simple way is to use an exception:

try:
    print(name)
except NameError:
    print("name não existe")
    
16.02.2015 / 04:20