Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python Module Importing – A Practical Guide with Examples

What are Python Modules?

A module is a single Python file that can contain variables, functions, and classes. When you name the file guru99.py, the module is accessed as guru99. Modules let you split a large program into logical pieces, keeping your code organized and reusable.

Why Import Modules?

To use code defined in another file, you must import it. Importing gives you access to the module’s functions, classes, and variables, just like the import keyword in languages such as JavaScript, Java, or Ruby.

Creating and Importing a Module

Let’s walk through a simple example.

Folder layout:

modtest/
    test.py
    display.py

1. Create test.py:

def display_message():
    return 'Welcome to Guru99 Tutorials!'

2. Create display.py and import test:

import test

print(test.display_message())

Running display.py prints:

Welcome to Guru99 Tutorials!

Importing a Class from a Module

Suppose Car.py defines a car class:

class Car:
    brand_name = 'BMW'
    model = 'Z4'
    manu_year = '2020'

    def __init__(self, brand_name, model, manu_year):
        self.brand_name = brand_name
        self.model = model
        self.manu_year = manu_year

    def car_details(self):
        print('Car brand is', self.brand_name)
        print('Car model is', self.model)
        print('Car manufacture year is', self.manu_year)

    def get_car_brand(self):
        print('Car brand is', self.brand_name)

    def get_car_model(self):
        print('Car model is', self.model)

Use it in display.py:

import Car
car_det = Car.Car('BMW', 'Z5', 2020)
print(car_det.brand_name)
car_det.car_details()
car_det.get_car_brand()
car_det.get_car_model()

Output:

BMW
Car brand is BMW
Car model is Z5
Car manufacture year is 2020
Car brand is BMW
Car model is Z5

Using from to Import Specific Items

When you only need a few functions or variables, import them directly:

from test import display_message
print(display_message())

If you attempt to use a name that wasn’t imported, Python raises a NameError:

from test import display_message
print(display_message1())

Importing Everything from a Module

Import the entire module with import test and prefix names with the module, or import all names into the current namespace with from test import *. The latter is convenient but can pollute the namespace.

Understanding dir()

The built‑in dir() function lists all attributes of an object, including those defined in a module:

import Car
print(dir(Car))

For standard libraries:

import json
print(dir(json))

Working with Packages

A package is a directory containing an __init__.py file and one or more modules. For example:

Directory layout:

mypackage/
    __init__.py
    module1.py
    module2.py
    module3.py

In module1.py:

def mod1_func1():
    print('Welcome to Module1 function1')

def mod1_func2():
    print('Welcome to Module1 function2')

# …

Import with an alias:

import mypackage.module1 as mod1

mod1.mod1_func1()
mod1.mod1_func2()

Python Module Search Path

When Python resolves an import, it checks:

  1. The current working directory.
  2. Built‑in modules.
  3. Directories listed in sys.path.

Inspect it with:

import sys
print(sys.path)

Using Aliases for Modules

Give a module a shorter name to improve readability:

import test as t
print(t.display_message())
print(t.my_name)

Absolute vs. Relative Imports

In a multi‑module project, you can refer to modules either by their full path (absolute) or relative to the current file.

Absolute Import Example

from package1.module1 import myfunc1
# or
import package1.module1
package1.module1.myfunc1()

Relative Import Example

from .module1 import myfunc1
# or
from .subpkg.module3 import myfunc3

Absolute imports are clearer and less error‑prone when a project is moved, but they can become verbose. Relative imports keep code concise but may be harder to trace in large projects.

Key Takeaways

Python

  1. Python Modules: Creation, Importing, and Advanced Usage
  2. Python Print() Function: A Practical Guide with Examples
  3. Master Python’s str.count(): How to Count Characters & Substrings with Examples
  4. Master Python `format()` Strings with Clear Examples
  5. Master Python's String.find() Method: Syntax, Examples & Alternatives
  6. Python round() Function Explained with Practical Examples
  7. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  8. Python timeit() – Measuring Execution Time with Practical Examples
  9. Python list.count(): Expert Guide with Practical Examples
  10. Python Modules: Organizing Your Code for Clarity and Reusability