Skip to content

Instantly share code, notes, and snippets.

@khornberg
Last active May 18, 2016 19:57
Show Gist options
  • Save khornberg/9735eda92a14006bc91a935eb2268c93 to your computer and use it in GitHub Desktop.
Save khornberg/9735eda92a14006bc91a935eb2268c93 to your computer and use it in GitHub Desktop.
Python subclass determined at runtime
# Based on http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Metaprogramming.html
class P1(object):
name = 'Parent1'
class P2(object):
name = 'Parent2'
K = 'P1'
class MetaBase(type):
def __new__(mcl, name, bases, nmspc):
return super(MetaBase, mcl).__new__(mcl, name, bases, nmspc)
class Meta(MetaBase):
def __new__(mcl, name, bases, nmspc):
bases = (P1,) if K is 'P1' else (P2,)
return super(Meta, mcl).__new__(mcl, name, bases, nmspc)
class C(object):
__metaclass__ = Meta
c = C()
print(c.__class__.__bases__, c.__class__) # ((<class '__main__.P1'>,), <class '__main__.C'>)
print(c.name) # Parent1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment