Quick survey: locals in comprehensions (Python 3 only)

Antoon Pardon antoon.pardon at vub.be
Tue Jun 26 06:55:02 EDT 2018


On 26-06-18 12:39, Steven D'Aprano wrote:
> On Tue, 26 Jun 2018 12:04:16 +0200, Antoon Pardon 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.
> Ah, I see. Thanks for the explanation.
>
> Given that locals() is capable of dealing with uninitialised local 
> variables without raising, would you like to revise your expectation?


Sure, I would now expect any |permutation of either a) [1, 2] or b) [1, 2, ||UnboundLocalError|]

-- 
Antoon Pardon.
||||




More information about the Python-list mailing list