Modules and packages

Every Python script is called a module. Python has been designed with reusability and ease of code in mind. For this reason, every Python file we create becomes a Python module and is eligible to be invoked or used within any other file or script. You might have learned in Java how to import classes and reuse them with other classes. The idea is pretty much the same here, except that we are importing the whole file as a module and we can reuse any method, class, or variable of the imported file. Let's take a look at an example. We will create two files, child.py and parent.py, and put the following code in each, as follows:

The first five lines belong to child.py, and the last eight lines belong to parent.py. We will run the parent, as shown in the output. It should be noted that the imported file can be given an alias. In our case, we imported the child and gave it the alias C. Finally, we called child_method() class of that module from the parent Python script.

Let's now try to explore Python packages and how they can be used. In Java, a package is nothing but a folder or directory that collects logically connected class files in Java. Packages do the same in Python; they collect logically connected Python modules. It is always recommended to use packages, as this keeps the code clean and makes it reusable and modular.

As mentioned earlier, a Python package is a normal directory. The only difference is that in order to make a normal directory behave like a Python package, we must place an empty __init__.py file inside the directory. This indicates to Python which directories it should use as packages. Let's go ahead and create a package called shapes. We will place an empty Python file called __init__.py and another file called area_finder.py inside it:

Let's now put the following code in the area_finder.py file. Let's also create another file called invoker.py and place it outside the shapes folder that we created. The code of the invoker is given on the right-hand side of the following image, while the code of the area_finder is given on the left-hand side:

The preceding code is a straightforward example of how to use packages in Python.We created a package called shapes and placed a file called area_finder in it, which will compute the area of a shape. Then, we went ahead and created a file called invoker.py outside the shapes folder, and imported the area_finder script from the package in multiple ways (for demonstration purposes). Finally, we used one of the aliases to invoke the find_area() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.143.181