Nested class structures

Diez B. Roggisch deetsNOSPAM at web.de
Sat Sep 11 08:29:34 EDT 2004


> 
>     This is why I want to define the classes inline, nested in the
> other class.  I'm trying to leverage the syntactic structure of class
> definitions to get nested structures of code.  It's somewhat akin to
> 
> a = { 'one': 1,
>     'nested': { 'two': 2, 'three': 3,
>     'nestnest': { 'four': 4, 'five': 5 }
>     }
>     'othernest': { 'six': 6 }
>     }
> 
>     . . . except that I want the ability to include arbitrary python
> code where I have 1, 2, 3 there (as dictionary values).  As far as
> I can tell, Python doesn't provide a way to define code as part of
> a larger expression like this, except in a class definition.

The only thing that comes to my mind is to create the classes from strings
you exec - that will allow you to captur the class before redefining it:

 
code = """class anon:
    def foo(_):
        print "%s"
"""

res = []
for i in "abc":
    exec(code % i)
    res.append(anon)
    
for c in res:
    c().foo()
    

Apart from that, I don't see any way to accomplish this - and for good
reasons: classes as well as functions are only declarations - that means
that they are stored in a sort of symbol table. And as there is no such
thing like an order of declartions, the only thing to access them is their
name. In languages that don't allow for rebinging an identifier, you'll get
an error when trying to. In python, its silently rebinded.

The question is: _why_ do you want to do this? How do you want to access the
anonymous classes, if you were able to create them?

Apart from that, I don't thing that a simple naming scheme like anon_1,
anon_2 and so on is too bad...


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list