How to import the class within the same directory or sub directory? How to import the class within the same directory or sub directory? python python

How to import the class within the same directory or sub directory?


Python 2

Make an empty file called __init__.py 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 Userfrom dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py 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.

bin/    main.py    classes/        user.py        dir.py

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

from classes.user import Userfrom classes.dir import Dir

Python 3

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

from .user import Userfrom .dir import Dir


I just learned (thanks to martineau's comment) that, in order to import classes from files within the same directory, you would now write in Python 3:

from .user import Userfrom .dir import Dir


In your main.py:

from user import Class

where Class is the name of the class you want to import.

If you want to call a method of Class, you can call it using:

Class.method

Note that there should be an empty __init__.py file in the same directory.


matomo