Reputation: 181
I am confused about how the usage of field() in dataclasses works. I have this (senseless) example:
from dataclasses import dataclass, field
@dataclass
class Person:
name: str = field(init=False)
def print_name(self):
print(self.name)
dieter = Person()
dieter.print_name()
I would expect this to create an empty string. However, this only happens, when I add the parameter default="". Evenmore, in pycharm, no syntax highlight complains, when I write following code:
name: int = field(init=False, default="")
What is the point of type hints, if there is not syntax highlighting? I don't really have any problem, I'm just trying to grasp, what is actually happening.
The usage case is, that I am creating a class, that later contains matplotlib axes, plots etc. Since they don't exist in the beginning, I only want to initialize them, so they are connected to the class, and can later be created.
Upvotes: 0
Views: 2593
Reputation: 531738
From the documentation (emphasis mine):
The
dataclass()
decorator examines the class to findfield
s. Afield
is defined as a class variable that has a type annotation. With two exceptions described below, nothing indataclass()
examines the type specified in the variable annotation.
So the type hint is mainly used as a flag to tell dataclass
to pay attention to the name.
The two exceptions are if the annotation is ClassVar
or InitVar
, used to indicate that the name is not an instance attribute, but either a class attribute or an init-only parameter, respectively.
What I consider a third exception is the new KW_ONLY
value introduced in Python 3.10, which indicates that the following fields cannot be passed as positional arguments to __init__
. (The "field" so annotated doesn't define a field at all, but it's still a decorated name whose type dataclass
pays attention to.)
Upvotes: 3