basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    Chapter 13PythonBigger code

    Classes in Python: custom types, self and dataclass

    A class bundles data and the functions that work on it into a custom type: each instance holds its own fields, and methods access them through self. Build a Service class for server services, learn __init__, __repr__ and @dataclass — and see when a class pays off and when a dict is enough.

    What you’ll get

    Once a script handles a dozen services, dicts like {"name": "traefik", "host": "web1", "port": 443} start getting fragile: a typo in "prot" raises no error on assignment, and helper functions like make_url(srv) live apart from the data. A Service class keeps fields and methods together:

    # services.py
    class Service:
        def __init__(self, name, host, port=443):
            self.name = name
            self.host = host
            self.port = port
    
        def url(self):
            scheme = "https" if self.port == 443 else "http"
            return f"{scheme}://{self.host}:{self.port}"
    
        def __repr__(self):
            return f"Service({self.name!r}, {self.host!r}, port={self.port})"
    
    
    web = Service("traefik", "web1", 443)
    api = Service("beszel", "web1", 8090)
    
    print(web)
    print(web.url())
    print(api.url())
    python services.py
    # Service('traefik', 'web1', port=443)
    # https://web1:443
    # http://web1:8090

    web and api are two independent instances of the Service type. Each keeps its own name, host and port, and url() reads them through self.

    What will it print?
    class Counter:
        items = []
    
        def add(self, x):
            self.items.append(x)
    
    a = Counter()
    b = Counter()
    a.add("web1")
    print(b.items)
    What will it print?
    Answer:
    ['web1']

    items = [] in the class body is one shared list across all Counter instances. When a.add("web1") appends to it, b.items sees the change too. Create a separate list per instance inside __init__: self.items = [].

    How it works: blueprint and instances

    A class defines a new data type — the same kind as built-in str in Strings or Path in Files and paths. Calling type(web) returns <class '__main__.Service'>.

    class Service (methods: __init__, url, __repr__)
     ├── web ──► name="traefik", host="web1", port=443
     └── api ──► name="beszel",  host="web1", port=8090
    • __init__ runs when an object is created (Service("traefik", "web1", 443)) and sets the initial fields on self.
    • self refers to the specific instance. Calling web.url() passes web as the first argument automatically, just like calling Service.url(web).
    • __repr__ controls the string shown by print() and the debugger. Names with double underscores on both sides (dunder methods) are called by Python at the right moment.

    The short form: @dataclass

    Writing __init__, __repr__ and __eq__ by hand for every data record gets repetitive. The standard library’s dataclasses module generates them from a typed list of fields:

    from dataclasses import dataclass
    
    @dataclass
    class Service:
        name: str
        host: str
        port: int = 443
    
        def url(self):
            scheme = "https" if self.port == 443 else "http"
            return f"{scheme}://{self.host}:{self.port}"
    
    
    s1 = Service("traefik", "web1", 443)
    s2 = Service("traefik", "web1", 443)
    print(s1)
    print(s1 == s2)
    # Service(name='traefik', host='web1', port=443)
    # True

    Comparing two regular class instances with == gives False even when their fields match, because Python compares their memory addresses. @dataclass generates __eq__ automatically and compares field values instead.

    When a field needs an empty list or dict as its default, use field(default_factory=list) — Python rejects tags: list[str] = [] with a ValueError, blocking the shared-list bug from above.

    When you need a class and when a dict is enough

    Not every Python script needs classes: if two functions and a dict get the job done, adding a class only adds noise.

    Situation What to pick
    one-off script, 2–3 fields, or raw data straight from JSON dict (dict)
    fixed pair or triple with no methods ((host, port)) tuple (tuple)
    many uniform records needing clear field names and == comparison @dataclass
    data paired with behavior: methods, validation in __init__, mutable state class or @dataclass with methods

    Take it further

    Add port validation to Service.__init__: raise ValueError if port is outside 1..65535

    Check if not 1 <= port <= 65535: before assigning self.port = port and call raise ValueError(...).

    class Service:
        def __init__(self, name, host, port=443):
            if not 1 <= port <= 65535:
                raise ValueError(f"port out of range 1..65535: {port}")
            self.name = name
            self.host = host
            self.port = port
    Write a @dataclass Backup with fields name: str, size_mb: float, ok: bool = True and a summary(self) method

    Pick "OK" or "error" from self.ok inside summary, and return an f-string like f"{self.name}: {self.size_mb} MB ({status})".

    from dataclasses import dataclass
    
    @dataclass
    class Backup:
        name: str
        size_mb: float
        ok: bool = True
    
        def summary(self):
            status = "OK" if self.ok else "error"
            return f"{self.name}: {self.size_mb} MB ({status})"
    
    
    print(Backup("web1", 420.5).summary())
    # web1: 420.5 MB (OK)
    print(Backup("db1", 0.0, False).summary())
    # db1: 0.0 MB (error)
    Fix Counter from “What will it print?” so each instance has its own items list, and add a count(self) method

    Move self.items = [] inside def __init__(self):, and make count(self) return len(self.items).

    class Counter:
        def __init__(self):
            self.items = []
    
        def add(self, x):
            self.items.append(x)
    
        def count(self):
            return len(self.items)
    
    
    a = Counter()
    b = Counter()
    a.add("web1")
    print(a.count(), b.count())
    # 1 0

    If it doesn’t work

    TypeError: Service.url() takes 0 positional arguments but 1 was given

    Cause
    Missing self as the first parameter of a method: def url(): instead of def url(self):.
    Fix
    Put self first in every regular method — Python passes the instance there automatically on call.

    Changing a list field on one object changed it on all other objects

    Cause
    The list was declared right in the class body (items = []) instead of inside __init__. A class attribute is shared across every instance.
    Fix
    Create mutable fields (lists, dicts) inside __init__ as self.items = [], or in @dataclass with field(default_factory=list).

    AttributeError: 'Service' object has no attribute 'port'

    Cause
    You wrote port = port without self. in __init__ — the local variable vanished as soon as __init__ returned.
    Fix
    Store the field on the instance with self.: self.port = port.

    print(web) outputs <__main__.Service object at 0x…>

    Cause
    The class defines no __repr__ (or __str__), so Python prints the object’s memory address.
    Fix
    Add __repr__ or switch the class to @dataclass, which generates readable output on its own.

    ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory

    Cause
    A @dataclass field used a list or dict directly as a default: tags: list[str] = [].
    Fix
    Import field from dataclasses and write tags: list[str] = field(default_factory=list).