Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally import pieces of a python class

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

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

I would now like to import one or the other of two different implementations of some methods based on a parameter that becomes known only at instantiation time, e.g.,

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, doing like in the previous snippet restricts the visibility of foo10 and foo11 to the __init__ function only. Is there a way to achieve this class-wise?

like image 745
japs Avatar asked Oct 15 '25 06:10

japs


1 Answers

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
like image 189
Guybrush Avatar answered Oct 16 '25 22:10

Guybrush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!