Quick survey: locals in comprehensions (Python 3 only)

Jim Lee jim.lee at 1
Sun Jun 24 00:08:56 EDT 2018


From: Jim Lee <jlee54 at gmail.com>



On 06/23/2018 11:02 PM, Chris Angelico wrote:
> On Sun, Jun 24, 2018 at 3:44 PM, Jim Lee <jlee54 at gmail.com> wrote:
>>
>> On 06/23/2018 10:03 PM, Steven D'Aprano wrote:
>>> I'd like to run a quick survey. There is no right or wrong answer, since
>>> this is about your EXPECTATIONS, not what Python actually does.
>>>
>>> Given this function:
>>>
>>>
>>> def test():
>>>       a = 1
>>>       b = 2
>>>       result = [value for key, value in locals().items()]
>>>       return result
>>>
>>>
>>>
>>>
>>> what would you expect the result of calling test() to be? Is that the
>>> result you think is most useful? In your opinion, is this a useful
>>> feature, a misfeature, a bug, or "whatever"?
>>>
>>> I'm only looking for answers for Python 3. (The results in Python 2 are
>>> genuinely weird :-)
>>>
>>>
>> I would *expect* [1, 2, None], though I haven't actually tried running it.
>>
> Interesting. Where do you get the None from? Suppose it had been "key
> for..." instead of "value", what would the third key have been? ["a",
> "b", ...]
>
> ChrisA
There are three locals:Γ  a, b, and result.Γ  Since result cannot be assigned a
 value until the list comp has been evaluated, I would expect the comp to
return a value of "None" for result.Γ  An argument could also be made for [1,
2, []], but one thing I would *not* expect is [1, 2] or [2, 1]...

-Jim

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)



More information about the Python-list mailing list