Quick survey: locals in comprehensions (Python 3 only)
Tim Chase
python.list at tim.thechases.com
Mon Jun 25 09:59:04 EDT 2018
On 2018-06-23 23:08, Jim Lee wrote:
>>> On 06/23/2018 10:03 PM, Steven D'Aprano wrote:
>>>> 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?
>>>
>>> I would *expect* [1, 2, None], though I haven't actually tried
>>> running it.
>> Interesting. Where do you get the None from?
>
> There are three locals: a, b, and result.
However at the time locals() is called/evaluated, "result" hasn't yet
been created/defined, so I wouldn't expect to see any representation
of "result" in the return value. If it existed before the locals()
call, I would expect to see the value it had before the call:
def test()
a = 1
b = 2
result = "Steven"
result = [value for key, value in locals().items()]
return result
test() # return [1, 2, "Steven"]
-tkc
More information about the Python-list
mailing list