Skip to content
Advertisement

How do I call a function from another .py file? [duplicate]

file.py contains a function named function. How do I import it?

from file.py import function(a,b)

The above gives an error:

ImportError: No module named ‘file.py’; file is not a package

Advertisement

Answer

First, import function from file.py:

from file import function

Later, call the function using:

function(a, b)

Note that file is one of Python’s core modules, so I suggest you change the filename of file.py to something else.

Note that if you’re trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.

Advertisement