Discussion forum for David Beazley

Python 3 Cookbook's "Defining Classes Programmatically" Recipe


#1

Hi @dave,

The Python 3 Cookbook’s “Defining Classes Programmatically” recipe advises using types.new_class() and discusses the benefits over using type().

But it doesn’t compare against doing something like this does, where you define a (parametric) class inside a function and then return the new class that was created. Is that because you don’t consider that programmatic class creation?

In any case, I’d be curious to hear what you think about how this approach compares to using types.new_type().

One downside of types.new_type() is that it requires Python 3.3+. I guess the Python 3 Cookbook assumes that too, but for a library like bidict that still maintains Python 2 compatibility, it’s unfortunately not an option.

Thanks,
Josh


#2

Apologies for missing this earlier. I don’t really have any strong opinions about this–I’ve used both techniques in code before. I think the “programmatically” part of this recipe is probably more oriented towards things like bulk class creation–for instance, if you wanted to define a large number of classes from data in a list or some other source of data. For that case, you might be inclined to just call type() or types.new_type()


#3

Thanks for clarifying!