Organizing Our Modules #
After learning how to create a module in a file within the same directory as our Python script, we may want to organize our code better by creating a module in a folder. This allows us to group related functionality together and avoid cluttering our main code file.
Here are the steps to create a module inside a folder from our previous example:
-
Create an empty file named greetings/__init__.py. This will create a folder named greetings and a new file __init__.py. The file structure now looks like this:
. ├── main.py # Our main file ├── greetings.py └── greetings # A module folder └── __init__.pyThe__init__.pyfile is required when you want to treat a directory as a package and import modules from it. When Python imports a package, it looks for the__init__.pyfile in the directory, and if it's present, it knows that the directory is a package and can be imported. If the__init__.pyfile is missing, Python will not recognize the directory as a package and will not be able to import modules from it.In Python 3.3 and later, the
__init__.pyfile is no longer strictly required for a package. However, it's still a good practice to include it, as it makes the package more explicit and easier to understand for other developers. -
Create another file named greetings/functions.py, and copy the content of the file greetings.py into the new file we just created.
. ├── main.py # Our main file ├── greetings.py └── greetings # A module folder ├── __init__.py └── functions.py -
Now that we have both the file greetings.py and the module folder greetings, we need to remove the file greetings.py to avoid naming conflict and to make sure that whenever we import the module with
import greetingsorfrom greetings import ..., Python will look inside the folder instead of the greetings.py file. Remove the file by selecting the file, then clickxto the right of the file name.. ├── main.py # Our main file └── greetings # A module folder ├── __init__.py └── functions.py -
Now, we can use this module in our Python script by importing it. Update the code in main.py to import and use the
greet()function in the new file we created:from greetings.functions import greet greet("Alice") # Output: Hello Alice!You could also use another import syntax as well
from greetings import functions functions.greet("Alice") # Output: Hello Alice!
Exercise #
Follow the instructions in this lesson.
Tests #
- A new file
greetings/__init__.pyis created - A new file
greetings/functions.pyis created - Copy the function
greet()fromgreetings.pytogreetings/functions.py - Remove the file
greetings.py - Update the import path in the
main.pyfile - Call the function greet with the name
"Alice"
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules