Import and call identical function from all modules in the same directory

Craver2000

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?

Derte Trdelnik

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...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to import all modules from a directory in TypeScript?

Unable to import a function from file in same directory

Is it possible to import modules from all files in a directory, using a wildcard?

Is it possible to import modules from all files in a directory, using a wildcard?

Import all modules from a package

GO: Unable to import a function from file in same directory

Python cannot import one of two identical classes int the same directory

How to dynamically import ALL variables from ALL modules in a directory and put them in a list?

Import PowerShell scripts or modules from a directory

How to import modules from a different directory in python

Calling function between modules in same directory in python

How do I import a function from a file in a directory on the same 'level' as my current directory

Call same events from different modules in Opencart

How to import a file from the same directory in python?

Julia: import contents from package in same directory

How to import from a module in the same directory?

import files from same directory in VSCode

Cannot import file from same directory

from ... import OR import ... as for modules

Import modules and functions from a file in a specific directory in Julia 1.0

Understanding React.js import statment that imports modules from directory

How to import modules from a python directory set up like this?

Making all class methods call the same function

Call the same function for all rejected promisses

How to import two different things called the same from different modules?

All outputs from function are the same

Call a function from function inside the same controller

Javascript import all modules from a file as a global variables

Is it bad practise to import all functions from node modules?