0

I have a master module master.py and a helper function stored in a folder functions/helper1.py (I have many of these helper functions actually, which is why they are stored in a separate folder).

The helper1.py file looks like this:

def main():
    # Do some stuff
    return stuff

if __name__ == "__main__":
    main()

I need to import the helper function into the master module and I can think of two ways of doing it.

1. master.py:

from functions import helper1

def main():
    # Call helper1.
    vars = helper1.main()

if __name__ == "__main__":
    main()

2. master.py:

from functions.helper1 import main as helper1

def main():
    # Call helper1.
    vars = helper1()

if __name__ == "__main__":
    main()

I'd prefer 1. but I'm wondering if there's a recommended pythonic way of doing this?

Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • 3
    Why do you have a main function - and an `if __name__ == '__main__'` block - in your helpers file? Surely the reason for a helpers file is that it is not run directly. – Daniel Roseman Oct 12 '15 at 13:32
  • Name the functions something useful, then just use `from functions.helper1 import well_named_function`. Or put all the helper functions in a single `helpers` module and just `import helpers`. – Holloway Oct 12 '15 at 13:33
  • @DanielRoseman because at some point they *might* be called directly. Perhaps this is were I'm not doing things right? – Gabriel Oct 12 '15 at 13:34
  • @Trengot I've tried that but the "useful" name is already `helper1.py`. In this question it is a dummy name (ie: helper1), but in my actual code it is a descriptive name. I'd have to come up with a shorter version for each helper function so it would look like: `from functions.well_named_function import shorter_well_named_function` – Gabriel Oct 12 '15 at 13:37
  • 1
    Why do you have each function in a separate file? – Holloway Oct 12 '15 at 13:38
  • U can go through second option, More details http://effbot.org/zone/import-confusion.htm – Anup Oct 12 '15 at 13:40
  • Because I have *many* of these (sometimes more than one function in a single `helperX.py` file) and putting them all in a single file would make it huge. Also, they perform quite distinct tasks so keeping them separated is much more intuitive. – Gabriel Oct 12 '15 at 13:41
  • There is nothing special about a method called `main` in Python, Call your helper functions anything but main, and you'll at least make it easier for the next guy to read. From the trail of comments it appears you are trying to make this hard on yourself. If so, don't. – msw Oct 12 '15 at 14:36

0 Answers0