mardi 27 novembre 2018

creating nested classes in Python reflectively

I am trying to create nested Python classes using the 3 argument type function. I want to construct an analogue of this:

In [15]: class CC: 
    ...:     class DD: 
    ...:         pass 
    ...:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

The naive attempt is

In [17]: AA = type('AA', (), {'BB': type('BB', (), {})})                                                                                                                                                                                                                                                                                                                                                                                                                                       

but that is not quite right, since BB is actually created outside and before AA and is only put inside `AA later.

The difference isdemonstrated by:

In [18]: AA.BB                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
Out[18]: __main__.BB

In [16]: CC.DD                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
Out[16]: __main__.CC.DD

How can I create nested classes reflectively/dynamically that are completely equivalent to nested definitions?





Aucun commentaire:

Enregistrer un commentaire