Python Modules

Python Modules

Kishore V


Python Modules

A module in Python is simply a file that groups related code together. Think of it as a reusable toolbox that can contain functions, variables, and even classes. By organizing code into modules, your programs become cleaner, easier to maintain, and reusable across multiple projects.

In practice, any Python file with a .py extension can act as a module.

Creating Your Own Module

To create a module, write your Python code in a file and save it with a .py extension.

Example: create a file named utils.py


Using a Module

Once a module is created, you can use it in another Python file with the import statement.

Example: importing and using the module

Output:

Welcome to the system, Aarav!
Try it Yourself

When calling something from a module, always use the format: module_name.member_name.

Variables Inside a Module

Modules are not limited to functions—they can also store variables such as lists, dictionaries, or constants.

Example: update utils.py


Accessing module variables

Output:

1.0
Try it Yourself

Naming Rules for Modules

    • Module names can be anything meaningful

    • The file must end with .py

    • Avoid using Python reserved keywords

Using an Alias for a Module

Sometimes module names are long or conflict with other names. Python allows you to rename them during import using as.

Example: module aliasing

Output:

BlogApp
Try it Yourself

Built-in Python Modules

Python ships with many built-in modules that provide ready-made functionality, such as working with the OS, math operations, or system information.

Example: using the datetime module

Output:

2023-10-25 14:30:15.123456
Try it Yourself

Exploring a Module with dir()

The dir() function helps you inspect what functions and variables are available inside a module.

Example: listing members of a module

Output:

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Try it Yourself

This works for both built-in modules and user-defined modules.

Importing Specific Members from a Module

If you only need certain parts of a module, you can import them directly using the from keyword.

Example: module content


Import only what you need

Output:

GoCourse
Try it Yourself

When using from module import name, you can access name directly without the module prefix.

Our website uses cookies to enhance your experience. Learn More
Accept !