I was wondering whether the following would be a good idea
from dataclasses import dataclass, field, KW_ONLY, NO_FIELD
@dataclass
class Example:
a: bool = True
_: KW_ONLY
kw_a: bool: = False
b: str = field(init=False, default="hello")
_: NO_FIELD
c: str = "hello"
After NO_FIELD
the coder can define as many class attributes as needed without the attributes being considered for __init__
(and actions liks as_tuple
)
After having crafted many dataclasses I often find myself typing x: str = field(init=False, ...)
and having to specify field(
always feels like something out of place for attributes I want to have defined in the class but not managed by the dataclass machinery.
That was my first idea seeing how KW_ONLY
is already a sentinel with an equivalent function for keyword arguments.
Something else which has been in my mind would go along this lines
from dataclasses import dataclass, field, KW_ONLY, NO_FIELD
from typing import Annotated
@dataclass
class Example:
a: bool = True
_: KW_ONLY
kw_a: bool: = False
b: str = field(init=False, default="hello")
c: Annotated[str, NO_FIELD] = "hello"
Using Annotated
would allow the definition of attributes anywhere and still be clear. Incidentally, this could also be applied to KW_ONLY
avoiding the definition of _: KW_ONLY
, like this.
from dataclasses import dataclass, field, KW_ONLY, NO_FIELD
from typing import Annotated
@dataclass
class Example:
a: bool = True
kw_a: Annotated[bool, KW_ONLY] = False
b: str = field(init=False, default="hello")
c: Annotated[str, NO_FIELD] = "hello"
with what seems a more compact notation which does not sacrifice readability. I would even argue it improves readability by being explicit in what the character of kw_a
is, a keyword only argument.
Futhermore, no-init fields with a simple default value could also be added to this scheme and probably even for default_factory
ones
from dataclasses import dataclass, field, KW_ONLY, NO_FIELD, NO_INIT, NO_INIT_FACTORY
from typing import Annotated
@dataclass
class Example:
a: bool = True
kw_a: Annotated[bool, KW_ONLY] = False
b: Annotated[str, NO_INIT] = "hello"
c: Annotated[str, NO_FIELD] = "hello"
d: Annotated[list, NO_INIT_FACTORY] = list
Just an idea around dataclasses for your consideration guys.
Best regards