Python / Core Python Fundamentals Interview Questions
What are Python dataclasses and when should you use them instead of regular classes?
@dataclass (introduced in Python 3.7, PEP 557) is a class decorator that auto-generates boilerplate methods — __init__, __repr__, and __eq__ — from class-level field annotations. It removes the tedium of writing identical initialisation code for data-holding classes.
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list = field(default_factory=list) # mutable default
in_stock: bool = True
p = Product('Widget', 9.99, ['sale', 'new'])
print(p) # Product(name='Widget', price=9.99, tags=['sale', 'new'], in_stock=True)
print(p == Product('Widget', 9.99, ['sale', 'new'])) # True — __eq__ generated
# Frozen (immutable) dataclass — useful as dict key
@dataclass(frozen=True)
class Point:
x: float
y: float
pt = Point(1.0, 2.0)
print(hash(pt)) # hashable because frozenUse field(default_factory=list) for mutable defaults — the same reason you use None in regular functions; if you wrote tags: list = [] in a dataclass the annotation system handles it safely (unlike regular class attributes), but field(default_factory=list) is the explicit, recommended way.
Dataclasses are the right choice for plain data containers: API response models, configuration objects, records. For complex logic with many methods, regular classes are cleaner. For fully immutable value objects, frozen=True is the quick path. For validation and serialisation, libraries like Pydantic build on the dataclass concept and add runtime type checking.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
