[python-uk] TDD stuff in London, next two weeks (and list comprehension scoping)

Harry Percival harry.percival at gmail.com
Fri May 30 20:09:06 CEST 2014


ah.  I think i figured it out -- it's actually just a weird py.test thing.
something to do with its assert-introspection-voodoo...


On 30 May 2014 16:16, Roger Gammans <roger at gammascience.co.uk> wrote:

> On Fri, 2014-05-30 at 16:07 +0100, Sven Marnach wrote:
> > On 30 May 2014 15:49, Harry Percival <harry.percival at gmail.com> wrote:
> >         I had the problem outside of a class body, in a normal
> >         function...
> >
> >
> > The particular problem mentioned in the StackOverflow quesiton you
> > linked only ever occurs inside class bodies.  They are the only
> > enclosing scopes that are skipped in name lookups.  You can still
> > access class attributes of the class by using ClassName.attribute
> > inside the list comprehension, like you would have to do to access
> > class attributes from inside methods.
>
> Hmm. It quite odd, it appears to only affect the evaluation part of the
> list-comprehension too. Notice the way that a naked reference to a works
> as the argument to range() , but not when used in the expr part of the
> list comprehension.
>
> $ python3.3
> Python 3.3.3 (default, Dec  8 2013, 14:51:59)
> [GCC 4.8.2] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class X:
> ...    a = 3
> ...    b = [ y for y in range(a) ]
> ...
> >>> X.b
> [0, 1, 2]
> >>> class X:
> ...    a = 3
> ...    b = [ y*a for y in range(a) ]
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in X
>   File "<stdin>", line 3, in <listcomp>
> NameError: global name 'a' is not defined
> >>> class X:
> ...    a = 3
> ...    b = [ y*X.a for y in range(a) ]
> ...
> >>> X.b
> [0, 3, 6]
>
>
> --
> Roger Gammans <roger at gammascience.co.uk>
>



-- 
------------------------------
Harry J.W. Percival
------------------------------
Twitter: @hjwp
Mobile:  +44 (0) 78877 02511
Skype:         harry.percival
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-uk/attachments/20140530/e8ec522a/attachment.html>


More information about the python-uk mailing list