I am trying to dynamically pick a parent class in Python 2.7:
GLOBAL_CLASS_NAME = 'b'
class A(object):
def __init__(self, bar):
print('this is A with {}'.format(bar))
class B(object):
def __init__(self, bar):
print('this is B with {}'.format(bar))
class C(object):
def __init__(self, bar):
print('this is C with {}'.format(bar))
class DynamicClass(object):
def __new__(cls, class_name, *args, **kwargs):
if class_name == 'a':
new_cls = A
elif class_name == 'b':
new_cls = B
elif class_name == 'c':
new_cls = C
else:
raise ValueError('No test type defined in config')
return new_cls
class MyClass(DynamicClass(GLOBAL_CLASS_NAME)):
pass
foo = MyClass('baz')
print(isinstance(foo, B))
print(issubclass(MyClass, B))
Giving the output:
this is B with baz True True
This works as expected so far, however, I feel there are some serious design flaws going on.
Why am I doing this?
I have a config file which should alter the functionality of specific methods in certain classes. I have proposed to do this as follow:
- I have a number of concrete implementations of a base class (
A, B, C
in my example), one of which are then inherited by a child class (MyClass
). - The parent class must be selected by a variable in a config file (
GLOBAL_CLASS_NAME
). - The child class is then inherited by other classes, modifying the behavior of their methods.
My questions
Are there any design patterns I should look into which achieve this in an improved manner? Are there any gotchas here which are going to burn me? Is there a more pythonic way of achieving this?
type
instead? – Gareth Rees Jun 11 at 16:22GLOBAL_CLASS_NAME
before definingMyClass
. Is this also true in your use case? That is, are you able to load the configuration file before definingMyClass
? (This kind of difficulty is why we discourage you from posting hypothetical or pseudo-code — when all you have is pseudo-code, it's hard to establish what the actual requirements are.) – Gareth Rees Jun 11 at 16:43