Quick survey: locals in comprehensions (Python 3 only)

Paul Moore p.f.moore at gmail.com
Sun Jun 24 17:37:51 EDT 2018


On 24 June 2018 at 06:03, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> 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 :-)

My immediate reaction was "that's not something I'd want to do, so I
don't care (but I've a feeling it would be weird). On thinking some
more, I decided that [1, 2] made sense (but I still didn't actually
care). After reading Chris Angelico's analysis, I went back to my
first opinion (that I don't care, but I suspect it might be weird).

I'm aware of the background for this question. Is there any equivalent
question that doesn't use locals()? The reason I ask is that I see
locals() as "digging into implementation stuff" and sort of expect it
to act oddly in situations like this...

Paul



More information about the Python-list mailing list