0
0
Pythonprogramming~30 mins

__init__ file role in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Role of __init__.py in Python Packages
📖 Scenario: You are organizing a small Python project with multiple modules. You want to make sure Python treats your folder as a package so you can import your modules easily.
🎯 Goal: Learn how to create a Python package by adding an __init__.py file and understand its role in package initialization and imports.
📋 What You'll Learn
Create a folder structure with modules
Add an __init__.py file to the package folder
Use __init__.py to import specific functions
Import and use functions from the package in a script
💡 Why This Matters
🌍 Real World
Python packages are used to organize code into reusable modules, making it easier to maintain and share.
💼 Career
Understanding <code>__init__.py</code> is essential for Python developers to create and manage packages professionally.
Progress0 / 4 steps
1
Create a package folder with two modules
Create a folder named mypackage and inside it create two Python files named module1.py and module2.py. In module1.py, write a function called greet that returns the string "Hello from module1". In module2.py, write a function called farewell that returns the string "Goodbye from module2".
Python
Need a hint?

Each module is a separate file. Define one function per file as described.

2
Add an __init__.py file to the package
Inside the mypackage folder, create a file named __init__.py. In this file, import the greet function from module1 and the farewell function from module2.
Python
Need a hint?

Use relative imports starting with a dot to import from sibling modules.

3
Use the package imports in a script
Create a new Python script outside the mypackage folder named test_package.py. In this script, import the greet and farewell functions directly from mypackage. Call both functions and store their results in variables named hello_message and bye_message.
Python
Need a hint?

Import functions directly from the package name, not from individual modules.

4
Print the messages from the package functions
In test_package.py, add print statements to display the values of hello_message and bye_message.
Python
Need a hint?

Use two print statements, one for each message variable.