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.
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 onself.selfrefers to the specific instance. Callingweb.url()passeswebas the first argument automatically, just like callingService.url(web).__repr__controls the string shown byprint()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
Service.__init__: raise ValueError if port is outside 1..65535Check 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@dataclass Backup with fields name: str, size_mb: float, ok: bool = True and a summary(self) methodPick "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)Counter from “What will it print?” so each instance has its own items list, and add a count(self) methodMove 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 0If it doesn’t work
TypeError: Service.url() takes 0 positional arguments but 1 was given
- Cause
- Missing
selfas the first parameter of a method:def url():instead ofdef url(self):. - Fix
- Put
selffirst 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__asself.items = [], or in@dataclasswithfield(default_factory=list).
AttributeError: 'Service' object has no attribute 'port'
- Cause
- You wrote
port = portwithoutself.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
@dataclassfield used a list or dict directly as a default:tags: list[str] = []. - Fix
- Import
fieldfromdataclassesand writetags: list[str] = field(default_factory=list).