Quick survey: locals in comprehensions (Python 3 only)

Paul Moore p.f.moore at gmail.com
Tue Jun 26 06:27:16 EDT 2018


On 26 June 2018 at 11:09, Chris Angelico <rosuav at gmail.com> wrote:
> On Tue, Jun 26, 2018 at 8:04 PM, Antoon Pardon <antoon.pardon at vub.be> wrote:
>> On 26-06-18 11:22, Steven D'Aprano wrote:
>>> On Tue, 26 Jun 2018 10:20:38 +0200, Antoon Pardon wrote:
>>>
>>>>> def test():
>>>>>     a = 1
>>>>>     b = 2
>>>>>     result = [value for key, value in locals().items()]
>>>>>     return result
>>> [...]
>>>
>>>> I would expect an UnboundLocalError: local variable 'result' referenced
>>>> before assignment.
>>> Well, I did say that there's no right or wrong answers, but that
>>> surprises me. Which line do you expect to fail, and why do you think
>>> "result" is unbound?
>>
>> I would expect the third statement to fail because IMO we call the locals
>> function before result is bound. But result is a local variable so the
>> locals function will try to reference it, hence the UnboundLocalError.
>
> Would you expect the same behaviour from this function?
>
> def test():
>     a = 1
>     b = 2
>     result = locals()
>     return result

Regardless of the answer to that question, the message here is
basically "people don't have good intuition of how locals() works". Or
to put it another way, "code that uses locals() is already something
you should probably be checking the docs for if you care about the
details of what it does". Which agrees with my immediate reaction when
I saw the original question :-)

Paul



More information about the Python-list mailing list