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?

6
  • 1
    Umm... why not just import scriptN then access with scriptN.myfunc? Commented Jan 26, 2018 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? Commented Jan 26, 2018 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(). Commented Jan 26, 2018 at 10:34
  • @quamrana: So that means doing: import script2, script3, script4 and then scriptN.myfunc()? Commented Jan 26, 2018 at 10:58
  • Well, no, if you do import script2, script3, script4, then you will need to call script2.myfunc() or script3.myfunc() etc. Commented Jan 26, 2018 at 11:08

1 Answer 1

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...
Sign up to request clarification or add additional context in comments.

4 Comments

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?
sure, just loop over their names, see stackoverflow.com/questions/3207219/… for how to list a directory
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.
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 codereview.stackexchange.com for that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.