Search code examples
pythonpython-3.xpython-importimporterror

ImportError: How do I import a python module?


I've tried importing a Python module and failed. Here's my folder hierarchy:

package/
  folder/
    a.py
  utils/
    b.py

In module a.py I've tried importing b.py but received an ImportError.

How do I use function test from module b to a.py?

Files:

a.py

def usetest():
    test()

b.py

def test():
    print("hello world")

Solution

  • Importing of Python modules can be done with a few different syntaxes:

    • A simple import ... statement: import package.utils.b will now let you use package.utils.b.test(). Unfortunately it's quite long.
    • An import ... as ... statement: import package.utils.b as b will let you use b.test().
    • A from ... import ... statement: from package.utils.b import test will let you use test().
    • A from ... import ... as ... statement: from package.utils.b import test as test_me will let you use test_me().

    All of these options will run the exact same function. Try putting them at the top of a.py.

    Specifying the whole path, package.utils.b is called absolute form. You can also import in relative form:

    • import ..utils.b as b will let you use b.test(). Notice the 2 dots at the start, saying go up one folder.
    • from ..utils.b import test will let you use test().
    • from ..utils.b import test as test_me will let you use test_me().

    Each dot at the start specifies go up one folder, except one, which says "this folder".

    If the main file you try to run is inside the package (a.py), you should switch to the directory that contains package, and run the file using -m. In your case, switch to the directory that contains package, and run python -m package.folder.a.

    For more information about importing modules, see the Python Docs.

    You can also dynamically import Python modules using their full path. It's more advanced and won't be covered in this answer.