W3docs

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

In Python, you can use the import statement to import a module or class from a file within the same directory or a subdirectory.

In Python, you can use the import statement to import a module or class from a file within the same directory or a subdirectory.

To import a class from a file within the same directory, you can use the following syntax:

Import a module or class from a file within the same directory or a subdirectory in Python

from filename import ClassName

For example, if you have a file named example.py in the same directory and it contains a class named ExampleClass, you can import it like this:

Import a class from a module in Python

from example import ExampleClass

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

To import a class from a file within a subdirectory, you can use the following syntax:

Import a class from a file within a subdirectory in Python

from subdirectory.filename import ClassName

For example, if you have a file named example.py in a subdirectory named subdir and it contains a class named ExampleClass, you can import it like this:

Import a class from a file within a subdirectory in Python example

from subdir.example import ExampleClass

(Note: The subdirectory must contain an __init__.py file to be recognized as a Python package.)

You can also use import instead of from if you want to import the whole module and reference the class with the module name.

Import the whole module and reference the class with the module name in Python

import subdir.example

subdir.example.ExampleClass()

You can also use importlib to import modules dynamically, which is useful for conditional imports or plugin systems.

Using importlib to import modules dynamically in Python

import importlib

module = importlib.import_module("subdir.example")
example_class = getattr(module, "ExampleClass")

Please keep in mind that, in order to use import statement, the imported file should be in python path or in the same directory where the code is running.