Why are both locals() and globals() set?
Peng Yu
pengyu.ut at gmail.com
Fri Dec 22 23:01:04 EST 2017
Hi, The following example shows that both locals() and globals() are
updated when x and f are defined. Shouldn't they be considered and
global variable and functions only? Why does it make sense to set
locals() as well? Thanks.
$ cat ./main.py
#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:
d = dict()
d['l1'] = set(locals().keys())
d['g1'] = set(globals().keys())
x = 10
def f():
pass
d['l2'] = set(locals().keys())
d['g2'] = set(globals().keys())
print d['l2'] - d['l1']
print d['g2'] - d['g1']
import os.path
d['l3'] = set(locals().keys())
d['g3'] = set(globals().keys())
print d['l3'] - d['l2']
print d['g3'] - d['g2']
from os import path
d['l4'] = set(locals().keys())
d['g4'] = set(globals().keys())
print d['l4'] - d['l3']
print d['g4'] - d['g3']
$ ./main.py
set(['x', 'f'])
set(['x', 'f'])
set(['os'])
set(['os'])
set(['path'])
set(['path'])
--
Regards,
Peng
More information about the Python-list
mailing list