Python – How to import the class within the same directory or sub directory


I have a directory that stores all the .py files.

bin/ # where class User resides # where class Dir resides

I want to use classes from and in
How can I import these Python classes into
Furthermore, how can I import class User if is in a sub directory?


Best Solution

Python 2

Make an empty file called in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.


So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir