MODULES

In Modules and packages in Python, a module represents an organization of code. It is a program that contains the definition of data, functions and classes which become its attributes. A module forms a namespace that occupies an intermediate position in the namespace hierarchy. We have already covered namespaces.

Modules and scripts

A distinction is made between modules and scripts, a script represents the main flow of the program, modules can be considered as object libraries, function containers and classes mainly imported through the import statement in scripts or other modules.

IMPORTATION

The import takes place via the import statement, for example:

import module1

When this Statement is encountered Python performs a series of actions which are:

  1. Identification of the module
  2. Compilation in Bytecode (if necessary)
  3. Execution of the module

In the third step Python executes the Bytecode produced in the previous compilation phase from top to bottom one statement at a time, in this phase the functions are created, the classes are generated all the attributes so that we can use them inside the source file. Let’s see the first and second phase in a little more detail.

FINDING THE MODULE (MODULE SEARCH PATH)

The sequence of actions with which Python searches for a module is as follows:

  • The home directory of the program, i.e. the directory of the script that is importing the module. If it is found, the search ends and the module is compiled in Bytecode if necessary (ie if it is the first time it is imported or the module has been modified).
  • The directories indicated in the PYTHONPATH environment variable (if it exists as it is optional). If this variable has been set, Python looks for the module in all the directories indicated in it. If it is found, the search stops, otherwise it goes to point 3.
  • The standard library directories, the standard library is a directory created and maintained when Python is installed.
  • As a last resort, otherwise it means we did something wrong, the site-packages directory, which is a subdirectory of the directory where the standard library is located. The modules and frameworks produced by third parties are installed in this folder.

THE TRANSLATION IN BYTECODE

Bytecode

Modules but not scripts produce when imported a file containing the Bytecode of the module itself to which a name is assigned. The name consists of the name of the compiled module, the Python version (in this case 3.6) and the .pyc extension. Python stores these files compiled into Bytecode in a subdirectory of the directory where the module named __pycache__ resides. The compilation in Bytecode is done the first time the module is imported, or if the date of the source file is later than that of the compiled file, so if the file has been modified.

THE STATEMENT IMPORT

You can import multiple modules on the same line using the import statement, for example:

import module1, module2,….

As you can see in the figure, a module is also an object, more precisely it is an instance of the module class.

Import

All the objects that we are going to define in a module are attributes of that module, myFunc is an attribute of the modulo1 object and as such it is accessed using dot notation. Through the import statement, all the elements making up a module are imported, therefore all its attributes, data, methods and classes.

The statement import

THE KEYWORD AS

The as keyword allows you to define an alias for modulo1. In the source we can refer to it with the letter m.

keyword as

THE STATEMENT FROM

It is used to import only part of the module, the from keyword allows us to refer to an attribute in the source by simply using its name, no dot notation is required.

Statement from

AVOID COLLISIONS OF NAMES

It is possible having each module a different namespace, that collisions of names occur, two attributes can have the same name in two distinct modules as the namespaces are also distinct. To avoid this, you can use the as statement.

keyword as

THE ATTRIBUTE __NAME__

__name__ it is a default attribute of the modules that Python makes available to us. If a module is imported for example module1 referring to its __name__ attribute it returns the string “modulo1” precisely because it must not be confused since module1 is launched from the command line, where in this case the __name__ attribute gives us the string “__main__ “. This is important as in modulo1 we can make this distinction.

Attribute __name__
Attribute __name__

THE PACKAGE

A package is a directory that contains a collection of modules. They can have a hierarchical structure consisting of directories and subdirectories. They are the highest level of organization when we structure Python code. Suppose we put two modules in a directory dir_c subdirectory of dir_b.

Package

THE FILE __INIT__.PY

If we put a file called __init__.py inside the two directories, this determines for Python that this structure is a package. The presence of __init__.py is mandatory if we want to consider that this directory tree is a package. The structure is relative and not absolute, this means that the directory structure that constitutes a package must be contained in a directory that is part of the Module Search Path.

The file __init__.py

MODULE SEARCH PATH AND DIRECTORY

dir_a is the root of this package, and allows Python to locate it, just add the path of this directory in the PYTHONPATH environment variable. It is not part of the package as it does not have the __init__.py file. The __init__.py files contain the initialization code of the package, they are executed only once at the time of import.

Search Path

IMPORT OF A PACKAGE

Import of a Package
The file __init__.py
#CREARE LA SEGUENTE STRUTTURA DI DIRECTORY dir_a/dir_b/dir_c
#INSERIRE Modulo1 e Modulo2 in dir_c. CREARE LA VARIABILE D'AMBIENTE
#PYTHONPATH CHE PUNTA A dir_a.


#FILE myScript.py
import dir_b.dir_c.Modulo1 as m1
import dir_b.dir_c.Modulo2 as m2
#MODULO1
result = m1.numeroPrimo(11)
print(result)
#MODULO2
s = m2.studente('Mario','Rossi',23,'Giurisprudenza',2021)
v = s.denominazione()
print(v)
#*******************************************************************
#IL METODO VERIFICA SE IL NUMERO PASSATO IN INPUT
#E' UN NUMERO PRIMO


#Modulo1.py
def numeroPrimo(numero):
    divisore = 2
    while divisore <= numero:
        risultato = numero//divisore
        if divisore > risultato:
            s=f'{numero} non è un numero primo.'
            return s
        if numero % divisore > 0:
            divisore+=1
            continue
        else:
            s=f'{numero} è un numero primo.'
            a=f'divisore: {divisore}'
            c=f'resto: {numero % divisore}'
            print(a)
            print(c)
            return s
#Modulo2.py
class persona():
    def __init__(self,nome,cognome,eta):
        self.__nome__= nome
        self.__cognome__= cognome
        self.__eta__ = eta
    @property
    def nome(self):
        return self.__nome__
    @nome.setter
    def nome(self,nome):
        self.__nome__ = nome
    @property
    def cognome(self):
        return self.__cognome__
    @cognome.setter
    def cognome(self,cognome):
        self.__cognome__ = cognome
    @property
    def eta(self):
        return self.__eta__
    @eta.setter
    def eta(self,eta):
        self.__eta__ = eta
    def denominazione(self):
        s= f'Persona Nome: {self.nome} Cognome: {self.cognome} età: {self.eta}'
        return s

class studente(persona):
    def __init__(self,nome,cognome,eta,facolta,anno):
        self.__facolta__= facolta
        self.__anno__= anno
        super().__init__(nome,cognome,eta)
    @property
    def facolta(self):
        return self.__facolta__
    @facolta.setter
    def facolta(self,facolta):
        self.__facolta__ = facolta
    @property
    def anno(self):
        return self.__anno__
    @anno.setter
    def anno(self,anno):
        self.__anno__ = anno

VIEW GOOGLE MAPS

With three lines of code you can open in the default browser Google Maps with dynamically selected address. You can also make the program run as if it were an executable file. Let’s see how to do it. First I report the code.

from webbrowser import open
address = input('Inserisci la località:')
open('https://www.google.com/maps/place/' + address)

PROCEDIMENTO

In Visual Studio Code, right-click on Program.py and select View in File Explorer. In the window that opens, create a link to Program.py and modify it as shown in the figure. Obviously you will put your Paths:

Program
K

MODULES AND PACKAGE IN PYTHON LINK TO THE GITHUB CODE

GITHUB

MODULES AND PACKAGE IN PYTHON LINK TO PREVIOUS POST

PREVIOUS POST LINKS