cllamach
cllamach

Reputation: 441

Python locals() and globals() are the same?

I am messing around with local and global namespaces a bit, and i found a bit of a weird behaviour. If i do this...

len(globals().keys())

len(locals().keys())

I get two different results, first i get 344 and then i get 346. So for curiosity sake i want to know which keys are in my local but not on my global, so i do this.

[key for key in local().keys() if key not in globals().keys()]

And bam, nothing, returns a empty list.

Thinking maybe my code is faulty i try this.

g = [1,2,3,4]

l = [1,2,3,4,5,6]

[key for key in l if key not in g]

and returns as expected [5,6]

So, what's the reason that Python can't difference in the keys of locals() and globals().

Does it have to do with locals() == globals() and viceversa?

Thanks a lot.

Upvotes: 3

Views: 287

Answers (3)

anon582847382
anon582847382

Reputation: 20351

That is because in that case you are calling locals in the global scope. Whereas locals gets values in the current scope, globals returns all values in the global scope. This means that if you call locals in the global scope they will be the same. The difference is found when you call locals in a scope that is not global, for example; put that list comprehension (which is OK but for a few modifications) of yours into a function:

>>> def example(a, b, c):
...     return [k for k in locals().keys() if k not in globals()]
... 

>>> example(1, 2, 3)
['a', 'c', 'b']

So, in conclusion: yes, locals() == globals()- but only at the module level.

Upvotes: 5

TR.
TR.

Reputation: 200

You're probably using iPython. Try running it on the Python interpreter or on a script and that behavior will disappear.

Upvotes: 0

roippi
roippi

Reputation: 25954

At the module level, locals() == globals().

You are using iPython. It adds things to globals as you go.

len(locals().keys())
Out[4]: 27

len(locals().keys())
Out[5]: 29

len(locals().keys())
Out[6]: 31

len(locals().keys())
Out[7]: 33

Your list comp is evaluated all at once, so there is no time for ipython to inject things into globals(). If you execute it on different lines you would see:

s = locals().keys()

set(locals().keys()) - set(s)
Out[2]: set(['s', '_i2'])

Upvotes: 2

Related Questions