Moduli e pacchetti

Moduli e pacchetti Moduli e pacchetti.md

Moduli e pacchetti

Versione italiana

Moduli

Un modulo è un file Python (con estensione .py) che contiene codice, come funzioni, classi e variabili.

I moduli permettono di suddividere il codice in file separati, rendendolo più organizzato e facile da mantenere.

Importazione di moduli

  1. import:

    • Importa un intero modulo.
    • Esempio:
      import math print(math.sqrt(16)) # Output: 4.0
  2. from ... import:

    • Importa solo una parte specifica di un modulo.
    • Esempio:
      from math import sqrt print(sqrt(16)) # Output: 4.0

    Puoi anche importare più funzioni o classi:

    from math import sqrt, pi print(sqrt(16), pi) # Output: 4.0 3.141592653589793
  3. Alias:

    • Puoi rinominare un modulo o una funzione durante l'importazione usando as.
    • Esempio:
      import math as m print(m.sqrt(16)) # Output: 4.0

Creazione di moduli personalizzati

  1. Moduli personalizzati:

    • Un modulo è semplicemente un file Python (con estensione .py) che contiene funzioni, classi o variabili.
    • Esempio: crea un file chiamato mio_modulo.py con il seguente contenuto:
      def saluta(): print("Ciao dal modulo personalizzato!")
  2. Importazione del modulo personalizzato:

    • Puoi importare il modulo nello stesso modo in cui importi i moduli standard.
    • Esempio:
      import mio_modulo mio_modulo.saluta() # Output: Ciao dal modulo personalizzato!

Pacchetti e gerarchia di cartelle

  1. Pacchetti:

    • Un pacchetto è una raccolta di moduli organizzati in una gerarchia di cartelle.
    • Per creare un pacchetto, devi includere un file __init__.py in ogni cartella (può essere vuoto).
    • Struttura di esempio:
      mio_pacchetto/ __init__.py modulo1.py modulo2.py sottocartella/ __init__.py modulo3.py
  2. Importazione da pacchetti:

    • Puoi importare moduli da un pacchetto usando la notazione a punti.
    • Esempio:
      from mio_pacchetto import modulo1 from mio_pacchetto.sottocartella import modulo3

Uso di pip per installare pacchetti di terze parti

  1. pip:

    • È il gestore di pacchetti di Python. Ti permette di installare, aggiornare e rimuovere pacchetti di terze parti.
    • Comandi principali:
      • Installare un pacchetto: pip install nome_pacchetto
      • Aggiornare un pacchetto: pip install --upgrade nome_pacchetto
      • Rimuovere un pacchetto: pip uninstall nome_pacchetto
      • Elencare i pacchetti installati: pip list

    Esempio:

    pip install requests # Installa il pacchetto requests
  2. Ambienti virtuali:

    • È buona pratica usare ambienti virtuali (venv) per isolare le dipendenze dei progetti.
    • Creazione di un ambiente virtuale:
      python -m venv nome_ambiente
    • Attivazione:
      • Su Windows: nome_ambiente\Scripts\activate
      • Su macOS/Linux: source nome_ambiente/bin/activate

Introduzione ai moduli standard

Python include molti moduli standard che forniscono funzionalità utili. Ecco alcuni esempi:

  1. math:

    • Funzioni matematiche avanzate.
    • Esempio:
      import math print(math.sqrt(25)) # Output: 5.0 print(math.pi) # Output: 3.141592653589793
  2. random:

    • Generazione di numeri casuali.
    • Esempio:
      import random print(random.randint(1, 10)) # Numero casuale tra 1 e 10
  3. os:

    • Interazione con il sistema operativo (es. gestione di file e cartelle).
    • Esempio:
      import os print(os.getcwd()) # Restituisce la directory corrente
  4. sys:

    • Funzioni relative all'interprete Python.
    • Esempio:
      import sys print(sys.version) # Restituisce la versione di Python
  5. Altri moduli utili:

    • datetime: gestione di date e orari.
    • json: lavorare con dati in formato JSON.
    • re: espressioni regolari.
    • collections: strutture dati avanzate (es. defaultdict, Counter).

English version

Modules and Packages

Modules

A module is a Python file (with the extension .py) that contains code, such as functions, classes, and variables.

Modules allow you to split your code into separate files, making it more organized and easier to maintain.

Importing Modules

  1. import:
  • Import an entire module.
  • Example:
import math print(math.sqrt(16)) # Output: 4.0
  1. from ... import:
  • Import only a specific part of a module.
  • Example:
from math import sqrt print(sqrt(16)) # Output: 4.0

You can also import multiple functions or classes:

from math import sqrt, pi print(sqrt(16), pi) # Output: 4.0 3.141592653589793
  1. Aliases:
  • You can rename a module or function during import using as.
  • Example:
import math as m print(m.sqrt(16)) # Output: 4.0

Creating custom modules

  1. Custom modules:
  • A module is simply a Python file (with the extension .py) that contains functions, classes, or variables.
  • Example: Create a file called my_module.py with the following content:
def greet(): print("Hello from the custom module!")
  1. Importing the custom module:
  • You can import the module the same way you import standard modules.
  • Example:
import my_module my_module.greet() # Output: Hello from the custom module!

Packages and folder hierarchy

  1. Packages:
  • A package is a collection of modules organized in a folder hierarchy.
  • To create a package, you must include a __init__.py file in each folder (it can be empty).
  • Example structure:
my_package/ __init__.py module1.py module2.py subfolder/ __init__.py module3.py
  1. Import from packages:
  • You can import modules from a package using dot notation.
  • Example:
from my_package import module1 from my_package.subfolder import module3

Using pip to install third-party packages

  1. pip:
  • This is Python's package manager. It allows you to install, update, and remove third-party packages.
  • Main commands:
  • Install a package: pip install package_name
  • Upgrade a package: pip install --upgrade package_name
  • Remove a package: pip uninstall package_name
  • List installed packages: pip list

Example:

pip install requests # Install the requests package
  1. Virtual environments:
  • It is good practice to use virtual environments (venv) to isolate project dependencies.
  • Create a virtual environment:
python -m venv environment_name
  • Activation:
  • On Windows: environment_name\Scripts\activate
  • On macOS/Linux: source environment_name/bin/activate

Introduction to standard modules

Python includes many standard modules that provide useful functionality. Here are some examples:

  1. math:
  • Advanced mathematical functions.
  • Example:
import math print(math.sqrt(25)) # Output: 5.0 print(math.pi) # Output: 3.141592653589793
  1. random:
  • Random number generation.
  • Example:
import random print(random.randint(1, 10)) # Random number between 1 and 10
  1. os:
  • Interaction with the operating system (e.g. file and folder management).
  • Example:
import os print(os.getcwd()) # Returns the current directory
  1. sys:
  • Python interpreter related functions.
  • Example:
import sys print(sys.version) # Returns the Python version
  1. Other useful modules:
  • datetime: date and time handling.
  • json: working with JSON data.
  • re: regular expressions.
  • collections: advanced data structures (e.g. defaultdict, Counter).

Commenti