1

I have def myfunc() in script2.py, script3.py, script4.py. In script1.py, I want to call myfunc from script2, script3 and script 4.

In script1.py, rather than tediously listing out:

from script2.py import myfunc 
myfunc()
from script3.py import myfunc 
myfunc()
from script4.py import myfunc 
myfunc()

Is there a way that I can import myfunc from all scripts present in that same directory?

Craver2000
  • 433
  • 1
  • 7
  • 24
  • 1
    Umm... why not just `import scriptN` then access with `scriptN.myfunc`? – Mateen Ulhaq Jan 26 '18 at 10:23
  • Do you mean just changing the numbers (2,3,4) of the filenames to `N`? How about if my files were not sharing common prefixes in their name? – Craver2000 Jan 26 '18 at 10:24
  • I'm sure that Mateen means that you should have a series of `import scriptN` statements, then you can access each `myfunc` by using a longer name in each case, eg: `scriptN.myfunc()`. – quamrana Jan 26 '18 at 10:34
  • @quamrana: So that means doing: `import script2, script3, script4` and then `scriptN.myfunc()`? – Craver2000 Jan 26 '18 at 10:58
  • Well, no, if you do `import script2, script3, script4`, then you will need to call `script2.myfunc()` or `script3.myfunc()` etc. – quamrana Jan 26 '18 at 11:08
  • Ok, got it. So this method does shortens things abit. But I will still have to call the function for each of the imported modules. – Craver2000 Jan 26 '18 at 11:10

1 Answers1

2

what you are probably searching for is dynamic import

you can use the __import__ function to call your functions in a loop

for i in range(2, 5):
    try:
        script_module = __import__("script{}.py".format(i))
        script_module.myfunc()
    except ImportError:
        pass # or do whatever when this fails...
Derte Trdelnik
  • 2,656
  • 1
  • 22
  • 26
  • Thanks for the advice. What if my files have different names i.e. no common prefixes. The only common thing is that they reside in the same folder (other than the fact that they have the identical function of interest). Is there a way to call the function from all these files with dissimilar names? – Craver2000 Jan 26 '18 at 10:37
  • 1
    sure, just loop over their names, see https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory for how to list a directory – Derte Trdelnik Jan 26 '18 at 10:38
  • Just tried this method, works really well. Thanks! However, maybe it will be better to remove the `.py` as importing python files wouldn't require the `.py` extension to be written. – Craver2000 Jan 27 '18 at 19:04
  • I added the .py extension as it was in the question, you could have file.py.py , no way to know so I try only to answer the question and not do a code review... we have https://codereview.stackexchange.com for that – Derte Trdelnik Jan 28 '18 at 00:40