Is there a way to create subclasses on-the-fly?

Louis Thibault picture Louis Thibault · Feb 14, 2012 · Viewed 7.9k times · Source

I'm creating a game in which I have a somewhat complex method for creating entities.

When a level is loaded, the loading code reads a bunch of YAML files that contain attributes of all the different possible units. Using the YAML file, it creates a so-called EntityResource object. This EntityResource object serves as the authoritative source of information when spawning new units. The goal is twofold:

  1. Deter cheating by implementing a hash check on the output of the YAML file
  2. Aid in debugging by having all unit information come from a single, authoritative source.

These EntityResource objects are then fed into an EntityFactory object to produce units of a specific type.

My question is as follows. Is there a way to create sublcasses of EntityResource dynamically, based on the contents of the YAML file being read in?

Also, I would like each of these YAML-file-derived subclasses to be assigned a singleton metaclass. Any caveats?

Answer

jcollado picture jcollado · Feb 14, 2012

I'm not sure if this is what you're looking for, but you can use type to create subclasses dynamically:

SubClass = type('SubClass', (EntityResource,), {})

Edit: To understand how type works, you just need to translate how would you write the class and translate that into a type call. For example, if you want to write something like:

class SubClass(EntityResource):
    A=1
    B=2

then, that would be translated to:

 SubClass = type('SubClass', (EntityResource,), {'A': 1, 'B': 2})

where:

  • The first argument is just the class name
  • The second argument is the list of parent classes
  • The third argument is the dictionary initialize the class object. This includes not only class attributes, but also methods.