I am well aware of fact that classes can be declared dynamically in python using type
and have used it here and there. But I am still unclear what are the differences between these two functions.
def class_factory():
def init(self, attr):
self.attr = attr
class_ = type('DynamicClass', (), {'__init__' : init})
return class_
and
def class_factory():
class DynamicClass:
def __init__(self, attr):
self.attr = attr
return DynamicClass
I have seen first pattern used in a lot of code-bases (like django) but never seen second one so far. Still I find second one more clear, syntactically.
I am struggling to find proper explanation about why people use first pattern
for declaring dynamic classes and not second
one. I experimented with both functions and could not find any notable differences between classes obtained from both functions. I am hoping for a clear explanation about differences between above two patterns/syntaxes from any aspect (performance-wise or any other) they differ.
Thanks,