Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing functions into modules based on choice

Tags:

python

I have 2 Python modules (e.g. A.py & B.py) that have the same function names (the implementation is different though). A third module (C.py) has a function that requires the functions in A or B, depending on user choice.

A fourth module (D.py) will import either A or B, and then C.

How do I correctly setup the modules and imports?

# module A.py
def write():
    print('A')

# module B.py
def write():
    print('B')

# module C.py
def foo():
    write()

# module D.py (main executed module)
if choiceA:
    import A
    import C
else:
    import B
    import C

C.foo()
like image 618
Fabio Avatar asked Nov 22 '25 05:11

Fabio


1 Answers

This is essentially a basic case of a Strategy Pattern. Instead of doing a double-import and implicitly expecting module C to get the right module, you should just explicitly pass the appropriate selection for it to call.

Using modules A and B as before:

# module C.py
def foo(writer):
    writer.write()

# module D.py
import A
import B
import C

if choiceA:
  my_writer = A
elif choiceB:
  my_writer = B

C.foo(my_writer)

This will also continue to work exactly the same way if you choose to define A, B, and C as a class hierarchy instead of modules.

like image 175
tzaman Avatar answered Nov 23 '25 17:11

tzaman