Questions about `locals` builtin
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Feb 28 06:59:56 EST 2018
On Wed, 28 Feb 2018 18:01:42 +1100, Chris Angelico wrote:
> If you really want a list of ALL the local names in a function, you can
> look at its __code__ object, which has a tuple of variable names:
>
> print(func1.__code__.co_varnames)
>
> That information is static to the function, as it is indeed determined
> when the function is compiled.
Ho ho ho, not in Python 2 it isn't!!!
py> def bizarre():
... x = 1
... from math import * # oww my aching head!
... print 'sin' in locals()
... print sin
...
<stdin>:1: SyntaxWarning: import * only allowed at module level
py> bizarre()
True
<built-in function sin>
py> bizarre.__code__.co_varnames
('x',)
In Python 2, you can also use exec inside a function, for extra
obfuscatory goodness.
Python 3 locks down these loopholes, and ensures that locals inside
functions can be statically determined.
--
Steve
More information about the Python-list
mailing list