The Wayback Machine - https://web.archive.org/web/20240702222648/https://www.geeksforgeeks.org/import-the-class-within-the-same-directory-python/
Open In App

Import the Class within the Same Directory – Python

Last Updated : 24 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python classes are the methods to use object-oriented programming in Python. Python allows to create classes in the main project we are working on or in a new file that only stores the class definition. 
This article will explain how to import a class within the same directory or subdirectory in Python. For this article, one does not need any Python modules but, a version of Python 3. x. 

In order to utilize directories in any Python project, it is necessary to have an __init__.py file which works as a router to work between multiple files in a project. If one imports a module without an __init__.py file, they will receive an error as given in the following section.

Importing classes without __init__.py

When we import classes from a directory/subdirectory without __init__.py file in those directories/sub-directories, the python interpreter will throw the following error:

ImportError: attempted relative import with no known parent package

Using the __init__.py file to import classes

>CLASS  #directory name
    main.py  #main file
    name.py  #file in same directory containing ‘name’ class
   
   >sub  #sub-directory
        emp.py #sub-directory with file emp.py containing ’employ’ class

We will use this directory set up for demonstration purposes. Here, the parent directory CLASS has two files – main.py and name.py(contains name class), and a subdirectory sub which contains sub.py file which contains another class employ. Now we will show how to import classes from name.py and emp.py into the main.py file. 

To avoid the ImportError we saw in the previous section, we have to create an empty __init__.py file in the directory/sub-directory containing the required class definition. So, in our demonstration folder, we need to create two empty __init__.py files; one in the parent directory CLASS and the other in the sub-directory sub.
The new directory structure would look like this:

>CLASS  #directory name
    __init__.py #init file for parent directory
    main.py  #main file
   name.py  #file in same directory containing ‘name’ class
   
   >sub  #sub-directory
        __init__.py #init file for sub directory
        emp.py #sub-directory with file emp.py containing ’employ’ class

Following is the pictorial representation of the same.

project structure

Here, we can see that CLASS is the main directory, the sub is a subdirectory containing __init__.py and emp.py while the rest of the files are in the main directory. Now, the contents of the class definition files are given below.

Note: All the __init__.py files are empty as they are only required by the python interpreter for syntactical reasons.

name.py

Python3




# class definition
class name():
    def __init__(self, name):
        self.name = name
  
    def disp(self):
        print(self.name)


emp.py

Python3




# class
class employ():
    def __init__(self, employment):
        self.employment = employment
  
    def job(self):
        print(self.employment)


Importing classes in main.py

In the main.py file, to import the other 2 files, we will use the following syntax.

Python3




# import from same directory
from <filename> import <classname>
  
# import from sub directory
from <sub-directory>.<filename> import <classname>


The main.py file used in the example is as follows.

Python3




# Description: Importing modules from same directory
from name import name
# Description: Importing modules from sub directory
from sub.emp import employ
  
per = name("John")
per.disp()
  
emp = employ("Software Engineer")
emp.job()


Here we use the from keyword to define the file from which we are importing a class method; then we import the class by following its name with the import keyword. 
In the case of the classes that exist in a sub-directory, we use the dot (.) indexing method, which is,

<sub-dir>.<filename>

to define the file location and then import the required class from it. 

Output:

output

Note: If the __init__.py file contains some other reference/definition for the imported classes, python will choose those over the ones in the parent directory and subdirectory.

Example 2:

In this example, we shall see how to import classes at multiple levels of the directory. Consider a situation where the class we need to import lies within a sub-directory, that itself resides inside a sub-directory. We will import a class that resides in a second-level sub-directory. 

The directory structure is as follows:

structure

We have to import the class located inside the class_imp.py file into the main.py file. The class definition in class_imp.py is :

Python3




# class_imp.py
class Hello():
    def __init__(self, name):
        self.name = name
  
    def alert(self):
        print(f'Hello {self.name}!')


The driver program to import this class is as follows:

Python3




# main.py file
# importing the Hello class
from level_2.level_3.class_imp import Hello
  
person = Hello("Geeks")
person.alert()


Output:

output



Similar Reads

Python - Import from sibling directory
In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree: Directory Tree: root : | |__SiblingA: | \__A.py | |__SiblingB: | \__B.py In B.py we will create a simple function and in A.py we will import th
3 min read
Python - Import from parent directory
In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this. In the parent directory, we have a subdirectory, geeks.py file and in the subdirectory, we have a python file named temp.p
4 min read
Python - Import module outside directory
Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module into that file. If the module exists in the same directory as the file, we can directly import it using the syntax import module_name. But if it exists in a different direc
4 min read
Python – Import module from different directory
While working on big projects we may confront a situation where we want to import a module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory.  Note: A module is just a Pyt
4 min read
How to print all files within a directory using Python?
The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python. In this article, we will learn how to print all files within a directory using Python. T
3 min read
How to import a class from another file in Python ?
In this article, we will see How to import a class from another file in Python. Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole
2 min read
Why import star in Python is a bad idea
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it becomes very difficult at some times to say from w
3 min read
Create and Import modules in Python
In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and packages. A package is a collection of modules in dir
3 min read
How to import JSON File in MongoDB using Python?
Prerequisites: MongoDB and Python, Working With JSON Data in Python MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. JSON stands for JavaScript Object Notation. It is an open standard file format, and data int
2 min read
How to import an excel file into Python using Pandas?
It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a '.xlsx' format. Before we get started, we need to install a few libraries. pip install pandas pip install xlrd For importing an Excel file into Python using Pandas we have to us
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg