Asir Zhao
Asir Zhao

Reputation: 29

Check whether multiple variables exist in python

I want to check whether multiple variables exist in python. I've tried some ways, but I have no idea why this not work in Python.

This is my Python code, I use 'all' in my if condition

feature = [{'a':'A'}]
table = 'demo'
if all(var in locals() for var in ('feature', 'table')):
    print("all exist")
else:
    print("at least one not exists")

This output should be "all exist" while it turns out "at least one not exists", which confuse me a lot.

Upvotes: 0

Views: 1404

Answers (2)

kaya3
kaya3

Reputation: 51093

The problem is that you passed a generator function as the argument to the all function, so locals() is being called in that generator function's local scope, not the scope you called all from (where feature and table are defined).

To diagnose the bug, we can try this:

>>> all(print(locals()) for var in ('feature', 'table'))
{'var': 'feature', '.0': <tuple_iterator object at 0x7fef8edc27f0>}

Note how the locals in the generator function's scope are var (which holds the key you want to check for) and .0 which holds a reference to the iterator over the tuple ('feature', 'table'). Those are the only locals that are needed to do the iteration.

To solve this, call locals() from the right scope:

feature = [{'a':'A'}]
table = 'demo'

outer_locals = locals()

if all(var in outer_locals for var in ('feature', 'table')):
    print("all exist")
else:
    print("at least one not exists")

Output is now "all exist", as expected.

Upvotes: 4

U13-Forward
U13-Forward

Reputation: 71610

locals sometimes doesn't provide the dict you want, when it is in the same scope of where the variables are defined, i.e globals will work here:

feature = [{'a':'A'}]
table = 'demo'

if all(var in globals() for var in ('feature', 'table')):
    print("all exist")
else:
    print("at least one not exists")

Output:

all exist

But of course, I agree with @deceze, but @kaya3 proves a point.

Upvotes: 2

Related Questions