What is the isset equivalent of PHP in Python

Asked

Viewed 2,309 times

3

In PHP, if I want to know if a variable has been started, I use isset.

How can I do the same in Python?

  • That? https://answall.com/q/50206/101

2 answers

7


Natively has not.

If the need is to check only if the variable exists I recommend starting all variables with some value, such as None or False (depending on the need), there is no need to create something complex for it (see at the end of the answers the examples).

It is necessary to understand that the isset of PHP does much more than check if a variable exists, it also checks if a key exists or even can check if a string contains a minimum of catheters, which will allow you to check if the variable exists and check the string at the same time, so I’ll tell you straight away that exactly how isset PHP does not have in python.

Of course, if the intention is to check a variable only you could just try something like:

try:
    minhavar
    print('Variavel definida')
except NameError:
    print('Variavel não definida')

You could also use globals() to check the variables defined in the scope and create a proper function, something like:

def isset(nameVar):
    return nameVar in globals()

See more about this in this question:

And the use would be:

if isset('variavel'):
    print('Variavel definida')
else:
    print('Variavel não definida')

But it’s like I said, the isset PHP has a very specific behavior, so for every thing of isset would have to create a "test", PHP feature examples:

//Se a variavel for uma string, verifica se existe e se ela contém 3 caracteres
//o index de uma string começa pelo zero, ou seja o primeiro caractere é o zero, o segundo vai ser o 1 e assim por diante
if (isset($foo[2])) {
     ...
}

//Checando se uma variavel tem acesso a uma propriedade especifica (o valor não pode ser nulo)
if (isset($foo->bar)) {
     ...
}

//Checando se uma variavel de array tem acesso a uma chave e esta chave não é um valor nulo
if (isset($foo['bar'])) {
     ...
}

Note that even if a variable, key or property of an object exists the isset will return as false in PHP, that’s because NULL is the only exception.

It would be a little complex behavior to carry to Python, it is not impossible, but it will depend on your need, there is no reason to create a "monstrous" function in the code if you will not use everything, me personally Python would choose to define everything, right at the beginning of the script or the scope of a def setando with None maybe, for example:

foo = None
bar = None
baz = None

and check like this:

if foo is None:
    print('foo é nula')
else:
    print('foo foi definida')

Can simplify to:

foo = bar = baz = None

Or you can use the unpack, would be like this if it has 3 variables use *3, as in this example:

foo, bar, baz = (None,)*3

If you wish to set as False:

foo, bar, baz = (False,)*3

This helps to avoid a certain repetition of codes

  • 1

    What is the difference or advantage of using the form unpack, since the above example does the same thing in a more readable way?

  • @Diegosouza no advantage in the specific case, but in dynamic use perhaps with dictionaries would be more interesting. I only quote because I found it interesting.

  • @Anselmoblancodominguez Thanks for editing, it was pertinent.

  • It is good to remember that in a, b, c = [{}] * 3 the variables a, b and c point to the same dictionary, so if you’re going to do this, you’d better do a, b, c = {}, {}, {} to avoid confusion with the references. PS: I mentioned this because of the comments, not the answer.

  • @fernandosavio yes, pq are references, I believe I should have an answer on, similar to the case when declaring values standards in def, there are the changeable and immutable types.

2

As built-in functions locals() and globals(), indicate the local and global symbol tables respectively.

You can check if the variable

name_var

exist in those dictionaries as follows::

if 'nome_var' in locals():
    print('variável local')

or

'nome_var' in globals()

Practical but less recommended - because it is a function created primarily for use in the interactive python environment - would be to use the built-in Function say(), pointing to a list of names available in the current scope.

'nome_var' in dir()

Browser other questions tagged

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