badballs.blogg.se

Packages in python
Packages in python









Our package contains two sub-packages: client and server. We start simple, though, with just HTTP GET and POST requests and a simple HTTP server. Our aim is that this imaginary package, one day, contains all the tools one might need to work with the HTTP protocol. Let’s create a package named httptools in the current directory. They are often a good alternative when you find yourself using underscores in package names. Using sub-packages also helps you keep package and module names short and concise. You should use sub-packages to group related modules together. We now have the following tools in our belt to properly organize our Python code: The print statements in both _init_.py files are executed due to the import of our sub-package. If we run this program, the output will be: $ python3 main.py We can create a main.py file in the package_name folder with the following contents: import package_name.subpackage1 I’ve added simple print statements to all the _init_.py files to demonstrate. then the _init_.py file of subpackage1.first the _init_.py file of package_name is executed,.When importing the nested package from above, with import package_name.subpackage1, the _init_.py file of both package_name and subpackage1 are executed. When importing the package from above with import package_name, the _init_.py file is executed. The _init_.py file is a special file that is always executed when the package is imported. Īs you can see, packages are hierarchical, just like directories. Let’s first take a look at the structure of a package with sub-packages. I’ll show you how to do that in more detail in one of the sections below.

packages in python

We can use sub-packages to organize our code further. Īs mentioned, packages can contain sub-packages. The structure of a simple Python package with two modules is as follows. So a Python package is a folder that contains Python modules and an _init_.py file. You’ll learn exactly what this mysterious file is for and how you can use it to make your package easier to import from. Each package always contains a special file named _init_.py. A Python package can contain sub-packages, which are also directories containing modules. 5 Create a runnable package with _main_.pyĪ Python package is a directory that contains zero or more Python modules.











Packages in python