Python tutorials > Modules and Packages > Modules > How to create modules?
How to create modules?
Basic Module Creation
.py
extension (e.g., my_module.py
).
2. Define functions, classes, or variables: Add your code inside the file. In this example, we define a function greet()
and a variable message
.
3. Optional: You can include a if __name__ == "__main__":
block. This code will only execute when the module is run as a standalone script, not when it's imported by another module.
# my_module.py
def greet(name):
return f"Hello, {name}!"
message = "This is a module variable."
if __name__ == "__main__":
print(greet("World"))
print(message)
Importing and Using a Module
import
statement followed by the module name (without the .py
extension).
2. Access module members: Use the dot notation (module_name.member_name
) to access functions, classes, and variables defined within the module.
# main.py
import my_module
print(my_module.greet("Alice"))
print(my_module.message)
Running the Main Script
main.py
script, execute python main.py
in your terminal. The output will be:Hello, Alice!
This is a module variable.
Concepts behind the snippet
Reusability: Modules can be reused across multiple projects, reducing code duplication.
Namespace management: Modules create separate namespaces, preventing naming conflicts between different parts of your code.
Encapsulation: Modules can hide internal implementation details, exposing only a public interface.
Real-Life Use Case Section
Each module would contain related functions and classes, making the code easier to understand, test, and maintain.
Best Practices
__init__.py
file).
Interview Tip
When to use them
Memory footprint
Alternatives
Pros
Cons
FAQ
-
What is the difference between a module and a package?
A module is a single Python file (.py
). A package is a directory containing multiple modules and an__init__.py
file. Packages are used to organize larger projects into a hierarchical structure. -
How do I import a specific function from a module?
You can use thefrom ... import ...
syntax:from my_module import greet
. Then you can call the function directly:greet("Bob")
. -
What is the purpose of the
__init__.py
file in a package?
The__init__.py
file is required to tell Python that a directory should be treated as a package. It can be empty, or it can contain code to initialize the package or define what modules should be available when the package is imported.