Skip to content

Commit 6befebc

Browse files
committed
forgot to save tip
1 parent 087bcee commit 6befebc

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

index.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,10 @@ This file gets generated by [this script](index.py).
102102

103103
- [The power of context managers](notes/20231212064259.md)
104104

105+
## Dataclass
106+
107+
- [Keyword-only arguments for dataclasses](notes/20250710131114.md)
108+
105109
## Dataclasses
106110

107111
- [Dataclass field and post_init](notes/20240627192941.md)

notes/20250710131114.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,28 @@
11
# Keyword-only arguments for dataclasses
22

3-
Since 3.10
3+
You can force keyword-only arguments in dataclasses (Python 🐍 3.10+) 🔥
4+
5+
Just add `kw_only=True` - a small change that makes your code more readable and safer. No more guessing what positional values mean or accidentally swapping arguments:
6+
7+
```python
8+
from dataclasses import dataclass
9+
10+
@dataclass(kw_only=True)
11+
class Email:
12+
sender: str
13+
recipient: str
14+
subject: str
15+
body: str
16+
17+
# Email("alice", "bob", "Lunch?", "1pm?") # ❌ not allowed, gives TypeError
18+
19+
email = Email(
20+
sender="alice@example.com",
21+
recipient="bob@example.com",
22+
subject="Lunch?",
23+
body="Want to grab lunch at 1?",
24+
)
25+
# Email(sender='alice@example.com', recipient='bob@example.com', ...
26+
```
27+
28+
#dataclass

0 commit comments

Comments
 (0)