Questions about `locals` builtin

Chris Angelico rosuav at gmail.com
Wed Feb 28 08:54:23 EST 2018


On Wed, Feb 28, 2018 at 10:59 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> 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
> ...

The sin in question is that you're using a star import inside a
function. The penance is to kneel before the altar and recite PEP 20
nineteen times. And then cut down the tallest tree in the forest...
with... a debugger.

(When I tried that, I got a SyntaxWarning. Yay!)

ChrisA



More information about the Python-list mailing list