hugomg
hugomg

Reputation: 69934

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

I am working with an ORM that accepts classes as input and I need to be able to feed it some dynamically generated classes. Currently, I am 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 feels off by a bit: for example, both classes print as <class '__main__.Cls'> on the repl. While the name issue is not a big deal (I think I could work around it by setting __name__), I wonder if there are other things I am not aware of. So my question is: is there a better way to create classes dynamically or is my example mostly fine already?

Upvotes: 8

Views: 306

Answers (1)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

What is class? It is just an instance 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>
>>> a.s
'i am a member'
>>> a.double_s()
'i am a memberi am a member'

From the doc:

type(name, bases, dict)

Return a new type object. This is essentially a dynamic form of the class statement.

Upvotes: 10

Related Questions