Skip to main content

Python Package

·223 words·2 mins
Posts Essential 101 python
Table of Contents
Let’s dive into a Python fundamental concept called __init__.py.

Fundamental Concept
#

Using __init__.py, allows you to organiza your code into modular chunks, making it easier to manage and reuse.

This is like a blueprint for your package, where you can define common functions, variables or even import other modules.

How It Works
#

Creating my_package:

$ mkdir my_package
$ cd my_package
$ touch __init__.py
$ touch testing.py

Creating the function:

# testing.py
def greeting():
  print(f'Hello World')

Now, let’s import the package.

$ cd ..
$ touch main_test.py
# main_test.py
from my_package import testing
testing.greeting()

Should get the output ‘Hello World’.

This shows that the __init__.py makes the testing module accessible from within the my_package namespace.

Conclusion
#

__init__.py is a fundamental building block for creating structured and organized Python packages.

It helps to manage, organize and maintain your Python package code in much easier format. By providing a foundation for structured code, it facilitates the resue of components within the package.

It can enhances the clarity of the package structure, and mkeing it easier to share with others.

We can combine __init__.py and __main__.py, to allow us execute Python package as project (like python my_package). See the Python Project post.

Python Project
·221 words·2 mins
Posts Essential 101 python py-venv
Elegant way to execute Python project.

Links#

Related

Why __name__ == '__main__'?
·323 words·2 mins
Posts Essential 101 python
Wonder why we always start with if __name__ == '__main__': in Python?
Python Project
·221 words·2 mins
Posts Essential 101 python py-venv
Elegant way to execute Python project.
Use of f-string format() in Python
·242 words·2 mins
Posts 101 python
Using f-string in Python.