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?

Asked By: Bin Chen



from user import User 
from dir import Dir 
Answered By: ceth

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
Answered By: Amber

In your

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:


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

Answered By: user225312

To make it more simple to understand:

Step 1: lets go to one directory, where all will be included

$ cd /var/tmp

Step 2: now lets make a file which has a class name Class1 with some code

$ cat > <<EOF
class Class1:
    OKBLUE = '33[94m'
    ENDC = '33[0m'
    OK = OKBLUE + "[Class1 OK]: " + ENDC

Step 3: now lets make a file which has a class name Class2 with some code

$ cat > <<EOF
class Class2:
    OKBLUE = '33[94m'
    ENDC = '33[0m'
    OK = OKBLUE + "[Class2 OK]: " + ENDC

Step 4: now lets make one which will be execute once to use Class1 and Class2 from 2 different files

$ cat > <<EOF
"""this is how we are actually calling and  from that file loading Class1"""
from class1 import Class1 
"""this is how we are actually calling and  from that file loading Class2"""
from class2 import Class2

print Class1.OK
print Class2.OK

Step 5: Run the program

$ python

The output would be

[Class1 OK]: 
[Class2 OK]:
Answered By: user285594

You can import the module and have access through its name if you don’t want to mix functions and classes with yours

import util # imports


or you can import the functions and classes to your code

from util import clean, setup

you can use wildchar * to import everything in that module to your code

from util import *
Answered By: A.Zaben

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 User
from .dir import Dir
Answered By: ecp

Just too brief,
Create a file is classes directory and then import it to your script like following (Import all case)

from classes.myscript import *

Import selected classes only

from classes.myscript import User
from classes.myscript import Dir

Python 3

Same directory.


import class: SampleApp().

import log
if __name__ == "__main__":
    app = log.SampleApp()


directory is basic.

import in file:

import class: SampleApp().

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
Answered By: Yasith Praharshana

From python3.3 upwards, is no longer necessary. If the current directory of the console is the directory where the python script is located, everything works fine with

import user

However, this won’t work if called from a different directory, which does not contain
In that case, use

from . import user

This works even if you want to import the whole file instead of just a class from there.

Answered By: lucidbrot

to import from the same directory

from . import the_file_you_want_to_import 

to import from sub directory the directory should contain

file other than you files then

from directory import your_file

Answered By: rojo_hlerr

If and are not including classes then

from .user import User
from .dir import Dir

is not working. You should then import as

from . import user
from . import dir
Answered By: Andreas Foteas



from .user import User inside file


use from class.dir import Dir inside
or from class.usr import User inside

like so

Answered By: icharis

I’m not sure why this work but using Pycharm build from file_in_same_dir import class_name

The IDE complained about it but it seems it still worked. I’m using Python 3.7

Answered By: stingMantis

For python3

import from sibling: from .user import User
import from nephew: from .usr.user import User

Answered By: Iceberg

If you have in the same folder, you can easily import it like this:

import filename

I am using python3.7

Answered By: kobako
# My Python version: 3.7
# IDE: Pycharm 2021.1.2 Community

# Have "myLib" in folder "labs":

class Points:
    def __init__(self, x = 0, y = 0):
        self.__x = x
        self.__y = y
    def __str__(self):
        return f"x = {self.__x}, y = {self.__y}"

# Have "myFile" in (same) folder "labs":

from myFile import Point

p1 = Point(1, 4)
p2 = Point(1, 4)
print(f"p1: {p1}, p2: {p2}")

# Result:
# p1: x = 1, y = 4, p2: x = 1, y = 4

# Good Luck!
Answered By: Andreas Klein

For Python 3+, suppose you have this structure:


In your file, you can put from . import foo

then you can import foo in bar file

# A/
from foo import YourClass

The purpose of the files is to include optional initialization code that runs as different levels of a package are encountered. everything you put in the will be initialized during the package load.

Answered By: minglyu

Indeed Python does not provide an elegant solution for this everyday use-case. It is especially problematic when you are testing your code that eventually will be delivered as part of a Python package. Here is an approach that has worked for me:



And let’s say you want to import file2 from file1.

# In
     # This works when packaged as Python package
     from . import file2
     # This works when simply invoking file1 as a module (i.e. python file1)
     import file2

# rest of the code ...
Answered By: Aakash Sahai

I cannot submit an edit for the top answer, so based on some pointers given in comments above, another thing to try out is:

from subfolder.MyClassFile import MyClass

And that’s it. Just remember to have an empty file in our subfolder.

Just for reference, the solution works if your structure is something like this:

    subfolder/  <-- You want this contains the class MyClass.

Answered By: absay

In a sufficiently complicated project, we can’t do hello world with python imports. When all else fails I had some success with the following


The linter still complained so we could make the simple thing even more criminally insane:

 if __name__ == "__main__":  # pragma: no cover
     script_dir = Path(os.path.dirname(os.path.realpath(__file__)))
     sys.path.insert(0, os.path.abspath(script_dir.parents[1]))
 # endregion
Answered By: Niklas Rosencrantz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.