Python import class from another file

We can import classes from external files in Python through various methods: using the 'import' command for individual classes, importing multiple classes from a single file, dynamic imports, and managing imports from different directories.

Welcome to our blog on "Python Import Class from Another File." If you're new to Python programming or looking to organize your code more efficiently, you've come to the right place. This article will walk you through the process of importing all the classes from different files, allowing you to reuse code and keep your projects clean and organized. We'll explore various methods using import statements, including importing specific classes, importing multiple classes, and dynamically importing classes. 

Whether you're a budding programmer or an experienced coder, these tips will help you harness the power of Python's import system and streamline your projects with ease. Let's get started!

Importing a specific class from the same package by using the import command

To import a specific class from another file in Python, you can use the import command followed by the module name and then the desired class name. Let's say we have two files: file1.py and file2.py and in file1.py, we have a class called MyClass, and we want to use it in file2.py.

file1.py

class MyClass:

def init(self, name):

     self.name = name

def greet(self):

     return f"Hello, {self.name}!"


file2.py

from file1 import MyClass

obj = MyClass("Mayank")

print(obj.greet())  # Output: "Hello, Mayank!"

In the above example, we imported the MyClass from py file - file1.py into file2.py. Now, we can create an instance of MyClass and use its methods in file2.py.

Import multiple classes from the same directory using Import command

Python allows you to import multiple classes from a single file located in the same directory using the import command and separating the class names with commas. Let's say we have a file called utils.py that contains two classes, MathHelper and StringHelper, and we want to use both of them in another file.

utils.py

class MathHelper:

@staticmethod

def add(a, b):

     return a + b

class StringHelper:

@staticmethod

def reverse(text):

     return text[::-1]

main.py

from utils import MathHelper, StringHelper

result = MathHelper.add(3, 5)

print(result)  # Output: 8

text = "hello"

reversed_text = StringHelper.reverse(text)

print(reversed_text)  # Output: "olleh"

In this example, we imported both MathHelper and StringHelper classes from utils.py into main.py and used their methods.

Import all classes from the same folder or file using Import * command

To import all classes from one file or a folder, you can use the import * command. However, this approach is generally discouraged as it can lead to naming conflicts and make code harder to read and maintain. For demonstration purposes, let's consider a file called shapes.py that contains two classes, Circle and Rectangle.

shapes.py

class Circle:

def init(self, radius):

     self.radius = radius

def area(self):

     return 3.14 self.radius self.radius

class Rectangle:

def init(self, width, height):

     self.width = width

     self.height = height

def area(self):

     return self.width * self.height


class square:

def init(self, side):

self.side = side;


def area(self):

return self.side*self.side

main.py

from shapes import *

circle_obj = Circle(5)

circle_area = circle_obj.area()

print(circle_area)  # Output: 78.5

rectangle_obj = Rectangle(4, 6)

rectangle_area = rectangle_obj.area()

print(rectangle_area)  # Output: 24

As shown above, we imported all classes (Circle and Rectangle) from shapes.py using the import * command. However, it is recommended to import specific classes explicitly to maintain code clarity.

Import all classes from the parent folder using Import SYS command

If your classes are located in a different folder within the parent directory, you can use the sys.path.append() function to add that folder to the Python path. Let's assume we have a project structure like this:

project/

   └── utils/

    ├── init.py

    └── helper.py

   └── main.py


helper.py

class Helper:

@staticmethod

def say_hello(name):

     return f"Hello, {name}!"


main.py

import sys

sys.path.append("utils")

from helper import Helper

helper_obj = Helper()

message = helper_obj.say_hello("Mayank")

print(message)  # Output: "Hello, Mayank!"

By appending the utils folder to the Python path, we can import square object - Helper class from helper.py in main.py.

Import classes dynamically

Dynamic importing refers to the process of importing classes or modules at runtime, which means that the import statement is executed during the execution of the program, not during the initial parsing phase. This is particularly useful when you want to load modules or classes dynamically based on certain conditions or user inputs.

Example:

import importlib

class_name = "MyClass"

module_name = "file1"

module = importlib.import_module(module_name)

class_obj = getattr(module, class_name)

obj = class_obj("Mayank")

print(obj.greet())  # Output: "Hello, Mayank!"

In the given example, we have a scenario where we want to import a class named MyClass from a module named file1 dynamically.

First, we define two variables, class_name and module_name, which will hold the names of the class and the module we want to import dynamically. These names can be determined based on user input or other runtime conditions, making our program more dynamic.

Next, using the importlib.import_module() function, we dynamically load the specified module by passing the module_name variable as an argument. This function returns the module as an object, allowing us to work with its contents programmatically.

Once we have the dynamically imported module, we use the getattr() function to access the class within it. By providing the module object and the class_name variable as arguments, we retrieve the class object associated with the given class_name.

With the class object, class_obj, in hand, we can now create an instance of the class. We do this by calling class_obj as a function and passing any required arguments. In our example, the MyClass class takes a single argument, name, in its constructor. We pass the string John as the argument to create an instance of the class with the name Mayank

Finally, we use the dynamically created class instance, obj, to call the greet() method, which returns a personalized greeting. Since we passed Mayank as the name during the instance creation, the output will be Hello, Mayank!

Conclusion

Importing classes from different files is a fundamental aspect of Python programming. By using the import command, you can easily reuse code and organize your projects more efficiently. We covered various import methods, from importing specific classes to dynamic imports using importlib. Remember to keep your code clean and readable by importing only the classes you need and avoiding wildcard imports. With these techniques at your disposal, you can confidently tackle more extensive Python projects while maintaining code clarity and structure.

You can also check these blogs:

  1. Get current year in Python
  2. Jaccard similarity in Python
  3. Python JSON Validator
  4. Python count unique values in column
  5. rstrip vs strip in Python: Trimming whitespaces made easy
  6. Master String Trimming in Python
  7. Apply function to list in Python
  8. Dataframe to List in Python
  9. Get class name as string in Python
  10. File Renaming in Python