how.wtf

Python dataclasses with optional fields

· Thomas Taylor

How do I create dataclasses in Python with optional fields?

How does a dataclass work?

Dataclasses generate dunder methods on the user’s behalf. Instead of defining __init__, __eq__, etc. manually, these methods are provided out of the box simply be defining fields and their respestive types.

1from dataclasses import dataclass
2
3@dataclass
4class Person
5    name: str
6    age: int

Because the methods and constructor are generated, the attributes are checked and hardcoded.

Optional fields in dataclasses

There are options for making an argument optional with dataclasses.

Using Optional[str] and a default value

It is possible to make an optional argument by using a default value for the attribute.

 1from dataclasses import dataclass
 2from typing import Optional
 3
 4@dataclass
 5class Person
 6    name: str
 7    age: int
 8    email: Optional[str] = None
 9
10print(Person(name="john", age=35)) # Person(name='john', age=35, email=None)

Using InitVar

InitVar is passed to the __init__ and __post_init__ methods, but is not stored as a class attribute. This can be valuable for some use-cases.

If a movie is not published, mark it as hidden.

 1from dataclasses import dataclass, field, InitVar
 2from typing import Optional
 3
 4@dataclass
 5class Movie:
 6    title: str
 7    hidden: bool = field(init=False)
 8    is_published: InitVar[Optional[bool]] = True
 9
10    def __post_init__(self, is_published):
11        self.hidden = not(is_published)
12
13print(Movie(title="title", is_published=False)) # Movie(title='title', hidden=True)
14print(Movie(title="title", is_published=True)) # Movie(title='title', hidden=False)
15print(Movie(title="title")) # Movie(title='title', hidden=False)

#Python  

Reply to this post by email ↪