Why nested scope rules do not apply to inner Class?

Discussion in 'Python' started by Cousson, Benoit, Aug 12, 2008.

  1. Hi,

    I'd like to be able to use a nested class (C1) from another sibling nested class (C3). This looks very similar to the nested scopes of functions except that it does not work.

    class A(object):
    pass

    class B(object):

    class C1(object):
    pass

    class C2(C1):
    foo = A

    class C3(object):
    foo = C1

    The funny thing is that C2 can inherit from C1 but C3 cannot reference C1. B.C1 does not work either, but in that case it makes sense since B is still being defined.
    Is this a language limitation or something that does not make sense at all?

    I'm wondering as well if the new nonlocal statement will fix that in py3k?

    Thanks in advance,
    Benoit
     
    Cousson, Benoit, Aug 12, 2008
    #1
    1. Advertisements

  2. > I'm wondering as well if the new nonlocal statement will fix that in py3k?

    The "class C3" statement is executing before the "class B" statement
    has concluded, so at that time B does not exist in any scope at all,
    not even globals(). You could reference B.C1 inside a method because a
    method is executed AFTER the class is defined.
    class A(object):
    pass

    class B(object):

    class C1(object):
    pass

    class C2(C1):
    foo = A

    class C3(object):

    @staticmethod
    def test( ):
    print repr( B.C1 )
    print repr( B.C2 )

    B.C3.test()

    :)
     
    Salim Fadhley, Aug 12, 2008
    #2
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    1,213
    Paul Opal
    Oct 11, 2004
  2. E11
    Replies:
    1
    Views:
    5,735
    Thomas Weidenfeller
    Oct 12, 2005
  3. Stefan Siegl
    Replies:
    1
    Views:
    1,179
    Marrow
    Jul 18, 2003
  4. Andrew Collier

    scope rules in nested functions

    Andrew Collier, Jan 29, 2005, in forum: Python
    Replies:
    0
    Views:
    415
    Andrew Collier
    Jan 29, 2005
  5. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,825
    Smokey Grindel
    Dec 2, 2006
  6. Robin
    Replies:
    0
    Views:
    554
    Robin
    Jun 6, 2007
  7. Calvin Spealman
    Replies:
    5
    Views:
    383
    Bruno Desthuilliers
    Aug 14, 2008
  8. Cousson, Benoit
    Replies:
    3
    Views:
    407
    Bruno Desthuilliers
    Aug 14, 2008
Loading...