lundi 23 décembre 2019

Design of Python conditional imports

I'm new to conditional importing in Python, and am considering two approaches for my module design. I'd appreciate input on why I might want to go with one vs. the other (or if a better alternative exists).

The problem

I have a program that will need to call structurally identical but distinct modules under different conditions. These modules all have the same functions, inputs, outputs, etc., the only difference is in what they do within their functions. For example,

# module_A.py
def get_the_thing(input):
    # do the thing specific to module A
    return thing

# module_B.py
def get_the_thing(input):
    # do the thing specific to module B
    return thing

Option 1

Based on an input value, I would just conditionally import the appropriate module, in line with this answer.

if val == 'A':
    import module_A
if val == 'B':
    import module_B

Option 2

I use the input variable to generate the module name as a string, then I call the function from the correct module based on that string using this method. I believe this requires me to import all the modules first.

import module_A
import module_B

in_var = get_input() # Say my input variable is 'A', meaning use Module A
module_nm = 'module_' + in_var
function_nm = 'get_the_thing'

getattr(globals()[module_nm], function_nm)(my_args)

The idea is this would call module_A.get_the_thing() by generating the module and function names at runtime. This is a frivolous example for only one function call, but in my actual case I'd be working with a list of functions, just wanted to keep things simple.

Any thoughts on whether either design is better, or if something superior exists to these two? Would appreciate any reasons why. Of course, A is more concise and probably more intuitive, but wasn't sure this necessarily equated to good design or differences in performance.

Aucun commentaire:

Enregistrer un commentaire