Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #68184 > unrolled thread

Re: Closure/method definition question for Python 2.7

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2014-03-10 18:26 -0600
Last post2014-03-10 18:26 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Closure/method definition question for Python 2.7 Ian Kelly <ian.g.kelly@gmail.com> - 2014-03-10 18:26 -0600

#68184 — Re: Closure/method definition question for Python 2.7

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-03-10 18:26 -0600
SubjectRe: Closure/method definition question for Python 2.7
Message-ID<mailman.8029.1394497630.18130.python-list@python.org>
On Mon, Mar 10, 2014 at 11:27 AM, Brunick, Gerard:(Constellation)
<Gerard.Brunick@constellation.com> wrote:
> The following code:
>
> ---
> class Test(object):
>     x = 10
>
>     def __init__(self):
>         self.y = x
>
> t = Test()
> ---
>
> raises
>
> NameError: global name 'x' is not defined.
>
> in Python 2.7.  I don't understand why.  I would assume that when __init__ is being defined, it is just a regular old function and x is a variable in an outer scope, so the function __init__ would close over the variable x.  Moreover, the variable x is not being modified, so this should be O.K.  For example, the following is fine (if nonsensical):

Class scopes and function scopes are not equivalent; class attributes
are not considered for closures.  Only local variables of outer
functions are considered.  At the time __init__ is defined the Test
class has not been created yet, and so the variable x is in local
scope then, e.g.:

    class Test(object):
        x = 10

        def __init__(self, y=x):
            self.y = y

This works fine, because the x is evaluated when the function is
created, while it's still in local scope.  But Python won't create a
closure for it.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web