0

I have two scripts main1 and main2 that need to be separated. They both call middle script (e.g. connection to database and query). The query itself comes from the sub1.py for main1 and sub2.py for main2.

Currently, I call middle with parameter indicating the origin. Could this be simplified?

#main1.py
import middle

middle.myfunction(arg_i, 'main1')


#main2.py
import middle

middle.myfunction(arg_i, 'main2')


#middle.py
import sub1, sub2

def myfunction(arg1, arg2):
    if arg2 == 'main1':
        ...
        sub1.anotherfunction

    elif arg2 == 'main2':
        ...
        sub2.yetanotherfunction

A potential solution is to duplicate myfunction in middle.py, i.e. create myfunction_main1 and myfunction_main2. But that does not seem elegant.

Bonus: I have additional functions in middle.py that are relevant only for main1, not main2. Since I am calling all functions from main1 by loop, I need to establish arg2 in them as well, else I get error on missing argument.

funs = [middle.fun1, middle.fun2, middle.myfunction]
for i in range(3):
    funs[i](arg_i, 'main1')
rtep
  • 13
  • 3
  • Can you not just pass in `myfunction` as `arg2` instead of a string? – Sayse Jan 31 '20 at 13:03
  • This question will help you out: https://stackoverflow.com/questions/3955790/python-circular-imports-once-again-aka-whats-wrong-with-this-design – Diogenis Siganos Jan 31 '20 at 13:06
  • Is there any logic behind versioning? Only filenames? Is `myfunction` some kind of launcher? Then it seems ok - `arg2` is kinda config for the launcher. That's how functions work. Give `arg2` some default value, for instance, `arg2='main1'`. –  Jan 31 '20 at 14:56

1 Answers1

0

You can pass __file__ as arg2

__file__ gives you the python file name which you can track in myfunction defined in middle.py.

main1.py
import middle

middle.myfunction(arg_i, __file__)


#main2.py
import middle

middle.myfunction(arg_i, __file__)


#middle.py
import sub1, sub2

def myfunction(arg1, arg2):
    if ('main1.py' in arg2):
        ...
        sub1.anotherfunction

    elif ('main2.py' in arg2):
        ...
        sub2.yetanotherfunction
Vikash Kumar
  • 296
  • 3
  • 10