Hisham Ragheb Hisham Ragheb - 4 months ago 19
Python Question

Why set is not in locals, globals or vars dictionaries

When I try to check if a set is available in current local scope, or in global scope, I always get the below error.

>>my_set = set()

>>my_set in locals()
>>Traceback (most recent call last):

File "<ipython-input-22-47b6756e3345>", line 1, in <module>
my_set in locals()

TypeError: unhashable type: 'set'
>>my_set in globals()
>>Traceback (most recent call last):

File "<ipython-input-22-47b6755f5503>", line 1, in <module>
my_set in globals()

TypeError: unhashable type: 'set'
>>my_set in vars()
>>Traceback (most recent call last):

File "<ipython-input-22-47b6755f9947>", line 1, in <module>
my_set in vars()

TypeError: unhashable type: 'set'


If set is not in any of these dictionaries (locals, globals or vars), where can I check if a set is defined?

Answer

You need to quote the name when checking.

>>> my_set = set()
>>> locals
<built-in function locals>
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'my_set': set([]), '__doc__': None, '__package__': None}
>>> 'my_set' in locals()
True
>>>