How to check if a variable was set in Python?

Asked

Viewed 5,279 times

10

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

  • 2

    Who gave the negative, can show what is the problem with the question?

3 answers

15


If the variable is local basically this is it:

if 'variavel' in locals():

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

if 'variavel' in globals():

And finally if she’s a member of some object:

if hasattr(objeto, 'variavel'):

I put in the Github for future reference.

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

  • In the first, second and third example, you use 'variable' as a string because it checks whether there is such a key in locals?

  • 1

    That’s basically it. Python like most dynamic languages doesn’t have real variables like in other more concrete languages. There is no memory space that this name refers to directly. Your remark is pertinent when you give an indication that the variables in the background are keys of a structure hash. One of the reasons for the performance of these languages is lower. But there are languages like Clipper/Harbour or Lua (if I’m not mistaken) that can allocate variables directly and provide better performance - though not comparable to static languages.

  • 1

    Of course this type of check is not possible on "real" variables, this type of check can only be done by the compiler because the variable disappears after compilation.

  • That one in works the same as in javascript?

  • Essentially yes. I don’t know if all semantics are equal but the base is equal to the operator in of the JS.

  • I gave a "-1" because the information "You can still check if it has any value, if it does not have, if it is None, it does not exist" is completely incorrect. The cases you list above are sufficient to check if a variable exists - if variavel is None will give a Nameerror exception if the variable does not actually exist.

  • 1

    @jsbueno you are absolutely right. Thank you for alerting me. Fixed.

  • @jsbueno is right. trying to do this direct check generates an error

  • 1

    I was advised for consistency not to verify that the variable does not exist. A friend of mine said "nonexistent variable is nonexistent variable". He advised me to leave the set variable as None, since I want to use it, but it still can’t have any value :)

  • Makes sense. In most cases checking if the variable exists shows a problem in the code. Some will even say that a variable might not exist is a problem in the language :)

  • 1

    @Qmechanic73 ready, I put in the answer your discovery. If you find new means, let me know to draw attention to the answer. Thank you.

Show 6 more comments

6

Another alternative way is the function dir():

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 treat 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())

2

Another simple way is to use an exception:

try:
    print(name)
except NameError:
    print("name não existe")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.