Back to Python
2026-03-067 min read

ES6 Modules (Python Programming)

Learn ES6 Modules (Python Programming) step by step with clear examples and exercises.

Title: ES6 Modules in Python Programming: A full guide

Why This Matters

ES6 modules, introduced in 2015, have revolutionized the way we structure and manage our code in JavaScript. As Python shares a similar syntax with JavaScript, understanding ES6 modules can help you write cleaner, more maintainable, and scalable Python code. This knowledge will be valuable for real-world projects, interviews, and debugging complex codebases.

ES6 modules offer several benefits over traditional Python importing methods, such as:

  • Code encapsulation: Modules provide a way to organize code into reusable, self-contained units that can be easily shared and managed.
  • Improved performance: By loading only the required parts of a module when needed, ES6 modules can help reduce memory usage and improve application start times.
  • Reduced naming conflicts: With explicit imports, it becomes easier to avoid naming conflicts between functions or variables in different modules.

Prerequisites

To follow this guide, you should have a basic understanding of Python programming concepts such as variables, functions, loops, and conditional statements. Familiarity with importing and exporting modules in Python is also beneficial but not mandatory. It's recommended to have a Python environment set up for testing the examples provided in this guide.

Core Concept

ES6 modules are a way to encapsulate JavaScript code into reusable, self-contained units. In Python, we can achieve similar functionality using the __init__.py file and the import and from ... import statements. Let's explore how to create and use ES6-style modules in our Python projects.

Creating a Module

To create an ES6 module in Python, simply save your code inside a file with a .py extension. For example, let's create a simple calculator module named calculator.py.

def add(a, b):
return a + b

def subtract(a, b):
return a - b

Export the functions for use in other scripts

__all__ = ['add', 'subtract']


### Importing and Using a Module

To import and use the above calculator module in another Python script, we can follow these steps:

1. Create a new file named `main.py`.
2. Use the `import` statement to include the calculator module.
3. Access the functions within the imported module using dot notation.

import calculator

result_add = calculator.add(5, 3)

result_subtract = calculator.subtract(7, 2)

print("Addition:", result_add)

print("Subtraction:", result_subtract)


### Exporting Functions from a Module

If you want to export specific functions from the module for use in other scripts, you can use the `from ... import` statement or the `__all__` list. Here's an updated version of our calculator module:

calculator.py

def add(a, b):

return a + b

def subtract(a, b):

return a - b

Export the functions for use in other scripts

__all__ = ['add', 'subtract']


Now, you can import and use these specific functions without needing to include the entire module.

main.py

from calculator import add, subtract

result_add = add(5, 3)

result_subtract = subtract(7, 2)

print("Addition:", result_add)

print("Subtraction:", result_subtract)


### Creating a Package

To create a package in Python, you can organize your modules and sub-packages into directories. Each directory should contain an `__init__.py` file to indicate that it's a package. Here's an example of creating a simple package named `my_package`.

my_package/

__init__.py

calculator/

__init__.py

calculator.py

shapes/

__init__.py

circle.py

rectangle.py


### Importing and Using a Package

To import and use the above package in another Python script, you can do the following:

1. Create a new file named `main.py`.
2. Use the `import` statement to include the entire package or specific modules within it.

import my_package

result_add = my_package.calculator.add(5, 3)

result_subtract = my_package.calculator.subtract(7, 2)

circle = my_package.shapes.circle.Circle(3)

rectangle = my_package.shapes.rectangle.Rectangle(4, 5)

Worked Example

Let's create a more complex example: a simple library for working with shapes. We'll have two classes—Circle and Rectangle. Both classes will require the radius or width and height to be set during initialization.

Creating the Shapes Module (shapes/circle.py)

class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * (self.radius ** 2)

Creating the Shapes Module (shapes/rectangle.py)

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

Creating the Shapes Package (shapes/__init__.py)

from .circle import Circle
from .rectangle import Rectangle

Using the Shapes Module (main.py)

import shapes

circle = shapes.Circle(3)
rectangle = shapes.Rectangle(4, 5)

print("Area of circle:", circle.area())
print("Area of rectangle:", rectangle.area())

Common Mistakes

  1. Forgetting to export functions or classes from the module: To make your functions and classes accessible in other scripts, you must explicitly export them using from ... import.
  2. Using the wrong syntax for importing modules: In Python, use the import statement to include the entire module, while from ... import is used to selectively import specific functions or classes.
  3. Not saving your modules with a .py extension: Make sure to save your code files with a .py extension for them to be recognized as Python modules.
  4. Importing a module without the .py extension: Ensure that you include the .py extension when importing modules, e.g., import calculator.
  5. Not using __all__ to control exports: If you want to control which functions or classes are exported from your module, use the __all__ list to specify them explicitly.
  6. Circular dependencies between modules: To avoid circular dependencies, you can use the importlib module to delay the import of a module until it is actually needed. Alternatively, you can refactor your code to remove or restructure the circular dependency.
  7. Not using __init__.py in packages: Each directory representing a package should contain an __init__.py file to indicate that it's a package and allow you to define module-level variables and functions that are available when the package is imported.
  8. Importing modules from the wrong location: Ensure that your import statements point to the correct location of the modules, especially when working with packages.

Practice Questions

  1. Create a module named utils that contains two functions: factorial(n) and fibonacci(n). Import these functions into another script and test their functionality.
  2. Write an ES6-style module for a simple bank account system, containing classes for Account, SavingsAccount, and CheckingAccount. Include methods for depositing, withdrawing, and checking the balance in each account type.
  3. Refactor the shapes example to create a utils package that contains the circle and rectangle modules, and modify the main.py script accordingly.
  4. Create a package named my_project with sub-packages models, views, and controllers. Within each sub-package, create a module that represents a model, view, or controller for a simple web application.

FAQ

  1. What is the difference between importing and exporting modules in Python? Importing allows you to use code from another module in your current script, while exporting makes specific functions or classes available for other scripts to use.
  2. Why should I use ES6-style modules in my Python projects? By organizing your code into self-contained units, ES6-style modules improve maintainability, readability, and scalability of your Python projects. They also offer better performance and reduced naming conflicts compared to traditional importing methods.
  3. Can I use ES6-style modules in older versions of Python? Starting from Python 3.5, you can use ES6-style modules by enabling the future library. However, native support for ES6 modules was added in Python 3.7. If you're using an older version of Python, consider upgrading to take advantage of this powerful feature.
  4. How do I handle circular dependencies between modules? To avoid circular dependencies, you can use the importlib module to delay the import of a module until it is actually needed. Alternatively, you can refactor your code to remove or restructure the circular dependency.
  5. What is the purpose of the __init__.py file in Python? The __init__.py file indicates that a directory should be treated as a package and allows you to define module-level variables and functions that are available when the package is imported. It's also used to initialize a package or module.
  6. How can I use type hinting in my Python modules? To use type hinting in your Python modules, simply add type annotations for function parameters and return values using the typing module. For example:
from typing import List, Union

def greet(name: str) -> str:
return f"Hello, {name}!"

def sum_numbers(numbers: List[Union[int, float]]) -> Union[int, float]:
total = 0
for number in numbers:
total += number
return total
ES6 Modules (Python Programming) | Python | XQA Learn