Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Modules

What is a Module?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules allow you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized and reusable.

Creating a Module

To create a module, you simply create a new Python file with a .py extension. Let's create a simple module named mymodule.py with the following content:

# mymodule.py
def greeting(name):
 return f"Hello, {name}"

Using a Module

To use the module you've created, you need to import it into another Python script or an interactive session. You can do this using the import statement.

For example, create a new Python file named test.py and add the following content:

import mymodule
print(mymodule.greeting("CrewAI"))

When you run test.py, you should see the following output:

Hello, CrewAI

Importing Specific Attributes from a Module

You can also import specific attributes from a module using the from ... import statement.

For example, you can import the greeting function directly:

from mymodule import greeting
print(greeting("CrewAI"))

This will yield the same output:

Hello, CrewAI

Using as to Rename a Module

Sometimes you might want to import a module but rename it to avoid naming conflicts or for convenience. You can do this using the as keyword.

For example:

import mymodule as mm
print(mm.greeting("CrewAI"))

This will also yield the same output:

Hello, CrewAI

Built-in Modules

Python comes with several built-in modules. You can import and use these modules in the same way as you use your custom modules.

For example, the math module provides mathematical functions:

import math
print(math.sqrt(16))

This will output:

4.0

Finding and Installing Modules

You can find and install additional modules using the Python Package Index (PyPI) and the pip tool. For example, to install the requests module, you can run:

pip install requests

After installing, you can use it in your code:

import requests
response = requests.get('https://api.github.com')
print(response.status_code)

This will output the status code of the HTTP response:

200

Conclusion

Modules are an essential part of Python programming that help in organizing and reusing code. By understanding how to create, import, and use modules, you can write more efficient and maintainable code.