Check whether a variable created through exec() exists

Asked

Viewed 33 times

0

Good evening, create an excerpt from a script that performs the creation of a variable through exec(), however, how can I verify that the variable exists through a for in range?

# criando a variável: host5 = 'ativo'
number = 5
foo = f"host{number}"
exec(foo + " = 'ativo'")

# verificando se a variável existe
for e in range(10):
    if f'host{e}' == 'ativo':
        print('ok')

The variable check part is only to demonstrate + or - as expected. Thank you staff.

2 answers

2

It is possible to use the locals() or globals()

The locals() lists existing variables within a function.

Already the globals() list the global variables.

In his example:

>>> number = 5
>>> foo = f"host{number}"
>>> exec(foo + " = 'ativo'")

>>> foo
'host5'

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'number': 5, 'foo': 'host5', 'host5': 'ativo'}

Therefore, just test as below:

>>> for e in range(10):
...     if f'host{e}' in globals():
...         if globals()[f'host{e}'] == 'ativo':
...             print('ok')

Or another way:

>>> for e in range(10):
...     var_teste = globals().get(f'host{e}', None)
...     if var_teste == 'ativo':
...         print('ok')

I hope it helps

1

You can use dir() Python and iterate over it to check if it exists

for e in dir():
    if e == 'host5':
        print('ok')

Or that way to check a range of names

for i in range(len(dir())):
    if f'host{i}' in dir():
        print('ok')

The dir() function returns the list of names in the current local scope.

  • Well-remembered dir(). However, I believe the goal was also to test the value. It would be possible with the dir()?

  • Fala @Paulo Marques , boa noite! I believe that with dir() you do not have this option. I answered by the statement that asks if the variable exists. Hug!

Browser other questions tagged

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