Python – Conditionally import fragments of Python classes

Conditionally import fragments of Python classes… here is a solution to the problem.

Conditionally import fragments of Python classes

Following the first example of this answer, I split the implementation of my class into different modules, similar to

class MyClass:
    from impl0 import foo00, foo01
    from impl1 import foo10, foo11

I now want to import one of two different implementations of some methods based on parameters that are only known at instantiation time, for example

class MyClass:
    from impl0 import foo00, foo01

def __init__(self, par):
        if par:
            from impl1 import foo10, foo11
        else:
            from alternative_impl1 ipmort foo10, foo11

However, like the previous code snippet, limit the visibility of foo10 and foo11 to the __init__ function. Is there a way to achieve this in terms of classes?

Solution

Assign the module to an instance (or class) variable:

if par: 
   from impl1 import foo10, foo11
else:
   from impl2 import foo10, foo11
self.foo10 = foo10
self.foo11 = foo11

Related Problems and Solutions