Python Import Statements

This post is a gift to my future self for when I no longer writer Python daily and need a refresher.

Chris Yeh has a wonderful post on the correct syntax to write import statements in Python.

The essence is, if you have a directory structure like:

awesome_project/
    run.py
    foo/
        __init__.py
        bar.py
        baz.py

In run.py:

from foo import bar

bar.Bar()

In baz.py:

from foo.bar import Bar

Bar()

This works for nested modules too:

awesome_project/
    run.py
    foo/
        __init__.py
        bar/
            __init__.py
            qux.py
        baz/
            __init__.py
            quux.py

In qux.py:

from foo.baz import quux

quux.Quux()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: