Created
August 7, 2019 11:34
-
-
Save a-recknagel/25975df0dd49b5a3608a3a6bef1768b6 to your computer and use it in GitHub Desktop.
inspect __init__ to skip classVars
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import InitVar, field, dataclass | |
import typing | |
import inspect | |
import re | |
CV = typing.ClassVar # this kills the regex ._. | |
@dataclass | |
class Foo: | |
var_1: int | |
var_2: float = field(init=False) | |
var_3: InitVar[str] | |
var_4: typing.ClassVar[int] = -1 | |
var_5: CV[int] = -2 | |
def __post_init__(self, var_3): | |
self.var_2 = int(var_3) + 1 | |
@classmethod | |
def from_dict(cls, env): | |
return cls(**{ | |
k: v for k, v in env.items() | |
if k in cls.__dataclass_fields__ | |
and cls.__dataclass_fields__[k].init | |
and not re.search(fr'{k}: .*ClassVar', inspect.getsource(cls)) | |
}) | |
# works | |
Foo.from_dict({'var_1': 4, 'var_2': 5, 'var_3': 7, 'var_4': 9}) | |
# doesn't work | |
Foo.from_dict({'var_1': 4, 'var_2': 5, 'var_3': 7, 'var_4': 9, 'var_5': 10}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment