title: Python subclass factory
body: <p>I have a number of subclasses of a single parent class and want to instantiate them according to strings in serialized data. My approach is to map the instantiating strings to classes and then create corresponding objects using a factory method:</p>
  
  <pre><code>class Superclass:
      @classmethod
      def get_instance(cls, string):
          return CLASSMAP[string]()
  
      def name(self):
          pass
  
  class Foo(Superclass):
      def name(self):
          return "my name is Foo"
  
  class Bar(Superclass):
      def name(self):
          return "i'm Bar"
  
  class Baz(Superclass):
      def name(self):
          return "i am called Baz"
  
  CLASSMAP = {
      'foo': Foo,
      'bar': Bar,
      'baz': Baz,
  }
  </code></pre>
  
  <p>I don't like having the CLASSMAP as a global dictionary, but I cannot define it as a member of Superclass right in the declaration due to the subclasses not having been defined yet (and they have to be defined after the superclass, of course). I can of course assign the class map into the class afterwards:</p>
  
  <pre><code>Superclass.CLASSMAP = {...}
  </code></pre>
  
  <p>and have Superclass' get_instance() method refer to the not-yet-existing field, but it seems even clunkier and prone to errors.</p>
  
  <p>Is there a more Pythonic approach to the whole pattern?</p>