If I had a file.py file
func1()
func2()
func3()
func4()
func5()
Is there a way to just import the whole file
import file
and call out the functions when needed instead of
from file import func1, func2, func3, func4, func5
If I had a file.py file
func1()
func2()
func3()
func4()
func5()
Is there a way to just import the whole file
import file
and call out the functions when needed instead of
from file import func1, func2, func3, func4, func5
By your import file
statement, you actually already have access to all of the functions inside file.py
, you simply need to preface them with the name of the file you imported, ie:
import file
file.func1()
file.func2()
etc...
If you truly wish not to have to preface where those functions came from (even though it is considered best practice to do so), from file import *
is the answer you're looking for!
Yes, import the file, then get each function by its name:
import file
func_names = ['func1', 'func2', ...]
for name in func_names:
getattr(file, name)()
If you don't mind moving your functions into a class as methods, you could import the class in your other module:
#module_one.py
class MyMethods:
@staticmethod
def method1():
return 'Hello world!'
@staticmethod
def method2():
return True
#module_two.py
from .module_one import MyMethods
x = MyMethods.method1()
y = MyMethods.method2()