What is the least bad way to create Python classes at runtime?

I work with ORM, which accepts classes as input, and I need to be able to feed some dynamically generated classes. I am currently doing something like this contrived example:

def make_cls(_param): def Cls(object): param = _param return Cls A, B = map(make_cls, ['A', 'B']) print A().foo print B().foo 

While this works fine, it is a little distracted: for example, both classes are printed as <class '__main__.Cls'> in repl. Although the name problem is not a big problem (I think I could get around it by setting __name__ ), I wonder if there are other things that I don't know about. So my question is: is there a better way to dynamically create classes, or is my example mostly fine?

+8
python class
source share
1 answer

What is a class? This is just an example of type . For example:

 >>> A = type('A', (object,), {'s': 'i am a member', 'double_s': lambda self: self.s * 2}) >>> a = A() >>> a <__main__.A object at 0x01229F50> >>> as 'i am a member' >>> a.double_s() 'i am a memberi am a member' 

From doc :

type (name, bas, dict)

Returns a new type object. This is essentially a dynamic form of a class operator.

+10
source share

All Articles