Moduli e pacchetti
Moduli e pacchetti.md
Uso di
Using
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
-
import
:- Importa un intero modulo.
- Esempio:import math print(math.sqrt(16)) # Output: 4.0
-
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 -
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
- Puoi rinominare un modulo o una funzione durante l'importazione usando
Creazione di moduli personalizzati
-
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!")
- Un modulo è semplicemente un file Python (con estensione
-
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
-
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
-
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
-
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
- Installare un pacchetto:
Esempio:
pip install requests # Installa il pacchetto requests -
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
- Su Windows:
- È buona pratica usare ambienti virtuali (
Introduzione ai moduli standard
Python include molti moduli standard che forniscono funzionalità utili. Ecco alcuni esempi:
-
math
:- Funzioni matematiche avanzate.
- Esempio:import math print(math.sqrt(25)) # Output: 5.0 print(math.pi) # Output: 3.141592653589793
-
random
:- Generazione di numeri casuali.
- Esempio:import random print(random.randint(1, 10)) # Numero casuale tra 1 e 10
-
os
:- Interazione con il sistema operativo (es. gestione di file e cartelle).
- Esempio:import os print(os.getcwd()) # Restituisce la directory corrente
-
sys
:- Funzioni relative all'interprete Python.
- Esempio:import sys print(sys.version) # Restituisce la versione di Python
-
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
import
:
- Import an entire module.
- Example:
import math
print(math.sqrt(16)) # Output: 4.0
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
- 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
- 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!")
- 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
- 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
- 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
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
- 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:
math
:
- Advanced mathematical functions.
- Example:
import math
print(math.sqrt(25)) # Output: 5.0
print(math.pi) # Output: 3.141592653589793
random
:
- Random number generation.
- Example:
import random
print(random.randint(1, 10)) # Random number between 1 and 10
os
:
- Interaction with the operating system (e.g. file and folder management).
- Example:
import os
print(os.getcwd()) # Returns the current directory
sys
:
- Python interpreter related functions.
- Example:
import sys
print(sys.version) # Returns the Python version
- 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
Posta un commento