๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ dataclasses.html
dataclasses โ€” Data Classes
In this example, the fields y and z will be marked as keyword-only fields: @dataclass class Point: x: float _: KW_ONLY y: float z: float p = Point(0, y=1.5, z=2.0) In a single dataclass, it is an error to specify more than one field whose type ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 72654545 โ€บ python-add-dataclass-to-set
Python Add Dataclass to Set - Stack Overflow
Instead of using a set, I think it makes more sense to use a dict type in this case. This should be O(1) for lookup, and also this way we can avoid next to find an element by its Speaker hashed value. Example below. from pprint import pprint from typing import List from dataclasses import dataclass, field @dataclass class Speaker: id: int name: str statements: List[str] = field(default_factory=list) def __eq__(self, other): return self.id == other.id and self.name == other.name def __hash__(self): return hash((self.id, self.name)) test = [(1, 'john', 'foo'), (1, 'john', 'bar'), (2, 'jane', 'near'), (2, 'george', 'far')] speakers = {} for id, name, statement in test: key = Speaker(id, name) speaker = speakers.setdefault(key, key) speaker.statements.append(statement) print(speakers) print() pprint(list(speakers.values()))
๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ how-to-use-python-data-classes
How to Use Python Data Classes (A Beginner's Guide) โ€“ Dataquest
May 12, 2025 - As we saw above, when using the dataclass decorator, the __init__, __repr__, and __eq__ methods are implemented for us. The creation of all these methods is set by the init, repr, and eq parameters of dataclass. These three parameters are True by default.
๐ŸŒ
Real Python
realpython.com โ€บ python-data-classes
Data Classes in Python (Guide) โ€“ Real Python
March 8, 2024 - For example, the following is an immutable version of the Position class you saw earlier: ... from dataclasses import dataclass @dataclass(frozen=True) class Position: name: str lon: float = 0.0 lat: float = 0.0
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ data-classes-in-python-set-3-dataclass-fields
Data Classes in Python | Set 3 (dataclass fields) - GeeksforGeeks
July 11, 2025 - A way to set default value should be provided when init is set to False. repr : If true (the default), this field is included in the string returned by the generated __repr__() method. compare : If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.). ... from dataclasses import dataclass, field @dataclass class GfgArticle: title: str = field(compare = False) author: str = field(repr = False) language: str = field(default ='Python3') upvotes: int = field(init = False, default = 0) # DataClass objects # Note the difference in their title value article1 = GfgArticle("DataClass", "vibhu4agarwal") article2 = GfgArticle("Python Packaging", "vibhu4agarwal") print(article1) print(article1.author) print(article1 == article2) Output:
๐ŸŒ
Hamy
hamy.xyz โ€บ blog โ€บ 2023-10-python-dataclasses
Python Dataclass best practices (and why you should use them) - HAMY
The easiest way I've found to solve this is to utilize the kw_only flag which makes it so that every field<>value must be explicitly set on the dataclass. Ofc you can still set a field<>value incorrectly but at least you're forced to read the field you're setting before doing so. ... """ Example 3: Explicit dataclasses * Show dataclasses at scale """ print("Example 3: Explicit dataclasses") @dataclass(frozen=True) class NoKeywordDC: aThousand: int # always one aTwelveHundred: int # always two aElevenHundred: int # always three many_dcs = [ NoKeywordDC( 1000, 1200, 1100 ), NoKeywordDC( 1000, 1200, 1100 ), NoKeywordDC( 1000, 1200, 1100 ), NoKeywordDC( 1000, 1100, 1200 ), NoKeywordDC( 1000, 1200, 1100 ) ] # Q: Which one is set wrong?
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-data-classes
Python Data Classes: A Comprehensive Tutorial | DataCamp
March 15, 2024 - Despite all their features, data ... functionality. Here is the Exercise class again: from dataclasses import dataclass @dataclass class Exercise: name: str reps: int sets: int weight: float ex1 = Exercise("Bench press", 10, 3, 52.5) # Verifying Exercise is a regular class ex1.name ...
๐ŸŒ
Florimond Manca
florimond.dev โ€บ en โ€บ posts โ€บ 2018 โ€บ 10 โ€บ reconciling-dataclasses-and-properties-in-python
Reconciling Dataclasses And Properties In Python - Florimond Manca
It takes advantage of Python's type annotations (if you still don't use them, you really should) to automatically generate boilerplate code you'd have to mechanically type yourself otherwise. As a point of comparison, here's how you would create a Vehicle class with a wheels attribute using a regular class declaration: class Vehicle: def __init__(self, wheels: int): self.wheels = wheels ยท Nothing fancy, really. Now, the @dataclass version:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ understanding-python-dataclasses
Understanding Python Dataclasses - GeeksforGeeks
July 15, 2025 - # default field example from dataclasses import dataclass, field # A class for holding an employees content @dataclass class employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int # default field set # city : str = "patna" city: str = field(default="patna") emp = employee("Satyam", "ksatyam858", 21) print(emp)
Find elsewhere
๐ŸŒ
InfoWorld
infoworld.com โ€บ home โ€บ software development โ€บ programming languages โ€บ python
How to use Python dataclasses | InfoWorld
October 22, 2025 - In this example, weโ€™ve created a __post_init__ method to set shelf_id to None if the bookโ€™s condition is initialized as "Discarded". Note how we use field to initialize shelf_id, and pass init as False to field. This means shelf_id wonโ€™t be initialized in __init__, but it is registered as a field with the dataclass overall, with type information. Another way to customize Python dataclass setup is to use the InitVar type.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ customizing-dataclass-initialization
Customizing dataclass initialization - Python Morsels
October 18, 2024 - All classes inherit from the built-in object class, and the __setattr__ method on object does the actual attribute-setting behind the scenes. So we can make new instances of this dataclass without an exception being raised: ... And we still can't directly assign to any of the attributes on this new dataclass because it's frozen, which is exactly what we want: >>> r.width = 5 Traceback (most recent call last): File "<python-input-3>", line 1, in <module> r.width = 5 ^^^^^^^ File "<string>", line 17, in __setattr__ dataclasses.FrozenInstanceError: cannot assign to field 'width'
๐ŸŒ
Linux Hint
linuxhint.com โ€บ dataclasses-python
How to Use Dataclasses in Python
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ dataclass
Python dataclass - using dataclass decorators in Python in custom classes
If the frozen parameter is set to True, we cannot assign values to fields. frozen.py ยท #!/usr/bin/python from dataclasses import dataclass @dataclass(frozen=True) class Person: name: str age: int p = Person('John Doe', 34) p.occupation = 'gardener' print(p) print(p.occupation) In the example, the frozen parameter is set to True.
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ stdlib โ€บ dataclasses
dataclasses | Python Standard Library โ€“ Real Python
>>> from dataclasses import dataclass >>> @dataclass ... class Point: ... x: int ... y: int ...
๐ŸŒ
Python
peps.python.org โ€บ pep-0557
PEP 557 โ€“ Data Classes | peps.python.org
There were undesirable side effects of this decision, so the final decision is to disallow the 3 known built-in mutable types: list, dict, and set. For a complete discussion of this and other options, see [14]. Sometimes the generated __init__ method does not suffice. For example, suppose you wanted to have an object to store *args and **kwargs: @dataclass(init=False) class ArgHolder: args: List[Any] kwargs: Mapping[Any, Any] def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs a = ArgHolder(1, 2, three=3)
๐ŸŒ
Python
typing.python.org โ€บ en โ€บ latest โ€บ spec โ€บ dataclasses.html
Dataclasses โ€” typing documentation
A dataclass field may be annotated with Final[...]. For example, x: Final[int] in a dataclass body specifies a dataclass field x, which will be initialized in the generated __init__ and cannot be assigned to thereafter. A Final dataclass field initialized in the class body is not a class attribute ...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ customizing-dataclass-fields
Customizing dataclass fields - Python Morsels
October 23, 2024 - >>> from dataclasses import dataclass >>> >>> @dataclass ... class Email: ... subject: str ... body: str ... sender: str ... recipients: list = [] ... cc: list = [] ... Traceback (most recent call last): File "<python-input-9>", line 1, in <module> @dataclass ^^^^^^^^^ File "/usr/lib/python3.13/dataclasses.py", line 1305, in dataclass return wrap(cls) File "/usr/lib/python3.13/dataclasses.py", line 1295, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only, slots, weakref_slot) File "/usr/lib/python3.13/dataclasses.py", line 1008, in _process_class
๐ŸŒ
Python Course
python-course.eu โ€บ oop โ€บ dataclasses-in-python.php
5. Dataclasses In Python | OOP | python-course.eu
Having an immutable class with a __hash__ method means that we can use our class in sets and dictionaries. We illustrate this in the following example: from dataclasses import dataclass @dataclass(frozen=True) class ImmutableRobot: name: str brandname: str robot1 = ImmutableRobot("Marvin", "NanoGuardian XR-2000") robot2 = ImmutableRobot("R2D2", "QuantumTech Sentinel-7") robot3 = ImmutableRobot("Marva", "MachinaMaster MM-42") # we create a set of Robots: robots = {robot1, robot2, robot3} print("The robots in the set robots:") for robo in robots: print(robo) # now a dictionary with robots as keys: activity = {robot1: 'activated', robot2: 'activated', robot3: 'deactivated'} print("\nAll the activated robots:") for robo, mode in activity.items(): if mode == 'activated': print(f"{robo} is activated")
๐ŸŒ
Medium
medium.com โ€บ @apps.merkurev โ€บ dataclasses-in-python-edca8c4b4242
Dataclasses in Python. Learn about the different ways toโ€ฆ | by AM | Medium
September 7, 2023 - The class syntax can be used with typing.NamedTuple starting from Python 3.6. This allows you to add your own methods or override existing ones, for example, define your own __str__ method. Book is still a subclass of tuple. import datetime from dataclasses import dataclass @dataclass(frozen=True) class Book: title: str author: str isbn: int pub_date: datetime.datetime rating: float = 4.98 # Book is not a subclass of tuple print(issubclass(Book, tuple)) # output: False book = Book( title='Learning Python', author='Mark Lutz', isbn=1449355730, pub_date=datetime.date(2013, 7, 30), ) print(book.title) # Learning Python print(book.rating) # 4.98, by default print(type(book)) # <class '__main__.Book'> print(book) # Book(title='Learning Python', author='Mark...)
๐ŸŒ
Medium
medium.com โ€บ alan โ€บ 5-things-you-should-know-about-dataclass-8c143b75596
๐Ÿ 5 things you should know about @dataclass | by Benoit Prioux | Alan Product and Technical Blog | Medium
July 5, 2022 - Itโ€™s a common Python gotchas (see here for mutable default arguments in functions). You must not use the direct default value, you have to use the utility dataclasses.field which allows you to give a factory to initialize your property. Here is the example for List: