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?
I want to use this to reflectively generate a graphene-sqlalchemy
api. The idiom there is to create an outer Graphene class with an inner Meta class pointing to the correponding SQLAchemy model class (http://docs.graphene-python.org/projects/sqlalchemy/en/latest/tutorial/#schema) eg:
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class UserModel(Base):
__tablename__ = 'department'
id = Column(Integer, primary_key=True)
name = Column(String)
last_name = Column(String)
from graphene_sqlalchemy import SQLAlchemyObjectType
class User(SQLAlchemyObjectType):
class Meta:
model = UserModel
# only return specified fields
only_fields = ("name",)
# exclude specified fields
exclude_fields = ("last_name",)
The User
class above is pretty cookie cutter and should be constructable programmatically from the UserModel
class. This should then be doable for an entire schema.