1

To simplify the problem, lets say I have 4 files. And right now I arrange them like the following

main.py (where I start the program)

global important_arg
important_arg = sys.argv[1]
if __name__ == "__main__":
    import worker_a
    import worker_b
    if important_arg == "0":
        worker = worker_a.worker()
        worker.run()
    elif important_arg == "1":
        worker = worker_b.worker()
        worker.run()

worker_a/worker_b.py

import main
import helper

class worker:
    def run(self):
        a = helper.dosth()
        b = helper.dosth_2()
        ....blah blah blah

helper.py (where worker_a and b both needed static function)

import main

important_arg = main.important_arg #This is not work I know, the problem is how to make this work.

def dosth():
   ...
   #I have tiny part need important_arg
   if important_arg == "0":
        print "This is worker A."
   elif important_arg == "1":
        print "This is worker B."
   ...

def dosth_2():
   ...

For sure in this pattern, my helper.py can no longer retrieve the important_arg from the main.py.

If I force it to run, no surprise,

The error will be

'module' object has no attribute 'important_arg'

How should I redesign the pattern, or anyway to pass that arg from the main.py to helper.py?

Besides, my last method is to covert the whole helper.py into a 'class'. But this is tedious as I need to add back tons of 'self.', unless I find passing the variable is impossible, I am unlikely to use this method right now.

MT-FreeHK
  • 2,462
  • 1
  • 13
  • 29
  • Pass important_arg as an arg into `worker.run()` and hence to `helper.dosth()` – smci Jul 27 '18 at 08:11
  • @smci, Yes, I originally think like this, but it is ok for just that small example, imagine if I have around 5~10 args like this, and ~30 times for `helper.dosth()`... Then whole screen will be my arguments.... – MT-FreeHK Jul 27 '18 at 08:14
  • 1
    Yes just use a function signature `run(self, *args)` or `run(self, *args, **kwargs)` so you don't need to specify each of them by name in the function signature. – smci Jul 27 '18 at 08:27
  • @smci, I see, I will take this as fall-back as it still take me quite a lot of time to change code. But I understand it will not affect the readability. Thanks. – MT-FreeHK Jul 27 '18 at 08:41
  • Related: [What does ** (double star/asterisk) and * (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – smci Jul 27 '18 at 09:16

0 Answers0