Skip to content

Latest commit

 

History

History
354 lines (221 loc) · 6.52 KB

2.4.md

File metadata and controls

354 lines (221 loc) · 6.52 KB

Moduły i importy / Modules and Imports


Why it matters / Dlaczego to ważne

Modules split code into logical pieces and let you reuse it.

Moduły dzielą kod na logiczne części i pozwalają go używać ponownie.

Putting everything in one file becomes unmanageable as projects grow.

Umieszczanie wszystkiego w jednym pliku staje się niemożliwe do zarządzania gdy projekty rosną.

Python's standard library and third-party packages are all modules you import.

Standardowa biblioteka Pythona i pakiety zewnętrzne to wszystko moduły które importujesz.

Documentation:

Python Modules Tutorial

Video:

Corey Schafer — Importing Modules (0:00–20:00)


Creating modules / Tworzenie modułów

Create math_utils.py:

Utwórz math_utils.py:

"""Math utility functions"""

def add(a: float, b: float) -> float:
    return a + b

def average(numbers: list[float]) -> float:
    if not numbers:
        raise ValueError("Empty list")
    return sum(numbers) / len(numbers)

PI = 3.14159

if __name__ == "__main__":
    print("Testing math_utils:")
    print(f"add(2, 3) = {add(2, 3)}")
    print(f"PI = {PI}")

Create main.py:

Utwórz main.py:

# Import entire module / Importuj cały moduł
import math_utils

result = math_utils.add(5, 3)
print(f"5 + 3 = {result}")

# Import specific functions / Importuj konkretne funkcje
from math_utils import average

numbers = [1, 2, 3, 4, 5]
print(f"Average: {average(numbers)}")

# Import with alias / Importuj z aliasem
import math_utils as mu

print(f"PI = {mu.PI}")

Run both:

Uruchom oba:

# Run module directly / Uruchom moduł bezpośrednio
uv run python math_utils.py

# Run main / Uruchom main
uv run python main.py

The __name__ trick / Trik __name__:

When you run a file directly, __name__ is "__main__".

Gdy uruchamiasz plik bezpośrednio, __name__ to "__main__".

When you import it, __name__ is the module name.

Gdy go importujesz, __name__ to nazwa modułu.

This lets you write test code that only runs when executed directly.

To pozwala pisać kod testowy uruchamiany tylko przy bezpośrednim wykonaniu.


Standard library / Standardowa biblioteka

Python comes with many built-in modules.

Python zawiera wiele wbudowanych modułów.

import math
import random
from datetime import datetime, timedelta
from pathlib import Path

# Math
print(f"Square root of 16: {math.sqrt(16)}")

# Random
print(f"Random 1-10: {random.randint(1, 10)}")

# Datetime
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}")

# Path
print(f"Current directory: {Path.cwd()}")

Packages / Pakiety

A package is a folder with multiple modules.

Pakiet to folder z wieloma modułami.

Create structure:

Utwórz strukturę:

mypackage/
    __init__.py
    string_tools.py
    math_tools.py

Create mypackage/__init__.py:

Utwórz mypackage/__init__.py:

from mypackage.string_tools import uppercase
from mypackage.math_tools import double

__all__ = ["uppercase", "double"]

Note: Relative imports (.string_tools) work but absolute imports are clearer in practice.

Uwaga: Relatywne importy (.string_tools) działają ale absolutne importy są czytelniejsze w praktyce.

Create mypackage/string_tools.py:

Utwórz mypackage/string_tools.py:

def uppercase(text: str) -> str:
    return text.upper()

Create mypackage/math_tools.py:

Utwórz mypackage/math_tools.py:

def double(n: float) -> float:
    return n * 2

Use the package:

Użyj pakietu:

from mypackage import uppercase, double

print(uppercase("hello"))
print(double(5))

Real-world example: utilities package / Przykład z życia: pakiet narzędziowy

This is how I organize utility code in my projects.

Tak organizuję kod narzędziowy w moich projektach.

utils/
    __init__.py
    file_utils.py
    string_utils.py

utils/file_utils.py:

from pathlib import Path
import json
import logging

logger = logging.getLogger(__name__)

def load_json(filepath: str) -> dict | None:
    try:
        return json.loads(Path(filepath).read_text())
    except Exception:
        logger.exception(f"Failed to load {filepath}")
        return None

def save_json(filepath: str, data: dict) -> bool:
    try:
        Path(filepath).write_text(json.dumps(data, indent=2))
        return True
    except Exception:
        logger.exception(f"Failed to save {filepath}")
        return False

utils/string_utils.py:

def clean_whitespace(text: str) -> str:
    return " ".join(text.split())

def truncate(text: str, max_length: int = 50) -> str:
    if len(text) <= max_length:
        return text
    return text[:max_length-3] + "..."

utils/__init__.py:

from utils.file_utils import load_json, save_json
from utils.string_utils import clean_whitespace, truncate

__all__ = ["load_json", "save_json", "clean_whitespace", "truncate"]

Usage:

Użycie:

from utils import load_json, truncate

data = load_json("config.json")
if data:
    name = truncate(data.get("name", ""), 20)
    print(f"Name: {name}")

Third-party packages / Pakiety zewnętrzne

Install packages with uv add:

Instaluj pakiety przez uv add:

uv add requests

Then use them:

Potem używaj ich:

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

Import best practices / Dobre praktyki importowania

Do:

  • Imports at top of file

    Importy na górze pliku

  • Group imports: stdlib, third-party, local

    Grupuj importy: stdlib, zewnętrzne, lokalne

  • Use specific imports when possible

    Używaj konkretnych importów gdy możliwe

Don't:

  • Use wildcard from module import *

    Używaj from module import *

  • Import inside functions (usually)

    Importuj w funkcjach (zazwyczaj)


Podsumowanie / Summary

After this section you can:

Po tej sekcji potrafisz:

  • create modules to organize code

    tworzyć moduły do organizacji kodu

  • import modules in different ways

    importować moduły różnymi sposobami

  • use the __name__ == "__main__" pattern

    używać wzorca __name__ == "__main__"

  • work with standard library

    pracować ze standardową biblioteką

  • create packages with multiple modules

    tworzyć pakiety z wieloma modułami

  • install third-party packages

    instalować pakiety zewnętrzne


Next: 2.5 — Praca z API