Quick survey: locals in comprehensions (Python 3 only)

Ben Finney ben+python at benfinney.id.au
Sun Jun 24 19:33:35 EDT 2018


Paul Moore <p.f.moore at gmail.com> writes:

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

> 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...

My understanding of Steven's question is to give an unambiguous way to:

* Express the question “which name bindings do you expect to exist in
  this local function scope, by the time of the ‘return’ statement?”.

* Avoid prejudicing the reader to expect any particular binding to be
  active.

One way to do the first, at the cost of losing the second, might be
this::

    def test():
        a = 1
        b = 2
        [value for key, value in dict().items()]
        print(a)
        print(b)
        print(key)
        print(value)

and then ask “Which of those statements do you expect to fail with
NameError?”.

But I may have misunderstood some nuance of what is being asked, which
is to be expected because Steven was deliberately trying to avoid having
the reader second-guess what the purpose of the code is.

-- 
 \     “I wish there was a knob on the TV to turn up the intelligence. |
  `\          There's a knob called ‘brightness’ but it doesn't work.” |
_o__)                                             —Eugene P. Gallagher |
Ben Finney




More information about the Python-list mailing list