Importing module from another subdirectory

dieter dieter at
Thu Apr 18 01:16:16 EDT 2019

Rich Shepard <rshepard at> writes:

> What is the proper syntax to import the model class in the model/
> subdirectory into a tkinter view module, e.g., The syntax,
> 'import model as m' fails because it is not in the same subdirectory as the
> importing module.
> The program directory tree is:
> bustrac/
>    README.rst
>    controller/
>    model/
>    scripts/
>    views/

Python knows about 2 kinds of "regular" imports:
absolute ones and relative ones. "Absolute" imports
are guided by "sys.path" -- in the simple case, a sequence
of folders containing modules and/or pacakges.
Relative imports are guided in a similar way by the current
packages's "__path__", which typically contains just one element -
the folder from which the current package was loaded.

When you start a script, Python adds the script's directory
to "sys.path". This makes (absolute) imports of other modules/packages in
this directory easy. Your structure, however, puts the infrastructure
elsewhere. I see two options for you:

1. put your scripts directly into "bustrac" (rather than a subdirectory)

2. extend "sys.path" in your scripts to contain the "bustrac" folder (
before you try to import infrastructure modules/packages)

Both options would allow you to import "model" via Python's "regular"
import. Apart from that you can use "importlib" services (--> runtime library
documentation) to import from any location you like.

More information about the Python-list mailing list