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


Groups > comp.lang.python > #68184

Re: Closure/method definition question for Python 2.7

References <71E0ECF7BE49E84CBD47914C9E19FFED2793AD54@exchm-omf-22.exelonds.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-03-10 18:26 -0600
Subject Re: Closure/method definition question for Python 2.7
Newsgroups comp.lang.python
Message-ID <mailman.8029.1394497630.18130.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web