0

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
Wadbo
  • 86
  • 1
  • 1
  • 8
  • 1
    `from file import *` – Paul M. Sep 18 '20 at 16:02
  • Does this answer your question? [Call a function from another file in Python](https://stackoverflow.com/questions/20309456/call-a-function-from-another-file-in-python) – Cilyan Sep 18 '20 at 16:04
  • 1
    other option is `import file` and then call `file.func1()` `file.func2()` etc. in my opinion it's better because it's make the code more readable as long as you must explicity set the origin of the function. – Yossi Levi Sep 18 '20 at 16:05
  • Actually, you can control what `from file import *` imports by defining what names are "public" an `__all__` list in the `file` module script. See [The `import` statement](https://docs.python.org/3/reference/simple_stmts.html?highlight=__all__#the-import-statement) in the documentation. – martineau Sep 18 '20 at 16:26

3 Answers3

3

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!

johnnybarrels
  • 344
  • 3
  • 7
1

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)()
go2nirvana
  • 1,598
  • 11
  • 20
0

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()
Rafael Sanchez
  • 394
  • 7
  • 20
  • this is superfluous to the original question, and the exact same behaviour is achieved simply by importing module_one, then calling module_one.func1(), module_one.func2() ... etc – johnnybarrels May 18 '22 at 02:47