53

I'd like to create a config dataclass in order to simplify whitelisting of and access to specific environment variables (typing os.environ['VAR_NAME'] is tedious relative to config.VAR_NAME). I therefore need to ignore unused environment variables in my dataclass's __init__ function, but I don't know how to extract the default __init__ in order to wrap it with, e.g., a function that also includes *_ as one of the arguments.

import os
from dataclasses import dataclass

@dataclass
class Config:
    VAR_NAME_1: str
    VAR_NAME_2: str

config = Config(**os.environ)

Running this gives me TypeError: __init__() got an unexpected keyword argument 'SOME_DEFAULT_ENV_VAR'.

martineau
  • 119,623
  • 25
  • 170
  • 301
Californian
  • 808
  • 1
  • 8
  • 15

5 Answers5

64

Cleaning the argument list before passing it to the constructor is probably the best way to go about it. I'd advice against writing your own __init__ function though, since the dataclass' __init__ does a couple of other convenient things that you'll lose by overriding it.

Also, since the argument-cleaning logic is very tightly bound to the behavior of the class and returns an instance, it might make sense to put it into a classmethod:

from dataclasses import dataclass
import inspect

@dataclass
class Config:
    var_1: str
    var_2: str

    @classmethod
    def from_dict(cls, env):      
        return cls(**{
            k: v for k, v in env.items() 
            if k in inspect.signature(cls).parameters
        })


# usage:
params = {'var_1': 'a', 'var_2': 'b', 'var_3': 'c'}
c = Config.from_dict(params)   # works without raising a TypeError 
print(c)
# prints: Config(var_1='a', var_2='b')
martineau
  • 119,623
  • 25
  • 170
  • 301
Arne
  • 17,706
  • 5
  • 83
  • 99
  • 1
    Don't use `cls.__annotations__`, use `dataclass.fields()` so you can introspect their configuration (e.g. ignore `init=False` fields). – Martijn Pieters Aug 06 '19 at 10:25
  • But you'd want `InitVar`s in this context, no? They also get skipped by `dataclasses.fields()`, so there might be a bit more I'll have to fix here. – Arne Aug 06 '19 at 10:42
  • @MartijnPieters `cls.__dataclass_fields__` works with `InitVar` inclusion and has access to the `init` field. – Arne Aug 06 '19 at 12:11
  • Unfortunately that mapping also includes `ClassVar` fields and the `init` flag is not set to `False` for those.. – Martijn Pieters Aug 06 '19 at 15:13
  • I don’t see a way to reliably achieve this without using the private API of the `dataclasses` module, actually :-/ – Martijn Pieters Aug 06 '19 at 15:15
  • Unless you instead introspected the `__init__` method. – Martijn Pieters Aug 06 '19 at 15:16
  • Updated with an `_is_classvar` check. I found no way to get it to work without it that didn't include essentially writing my own buggy version of it =( Introspecting `__init__` sounds even riskier, or do you see a way that doesn't boil down to using regexes? – Arne Aug 07 '19 at 06:50
  • [here](https://gist.github.com/a-recknagel/25975df0dd49b5a3608a3a6bef1768b6) is an alternative with `inspect.getsource`, which sadly can't give me `__init__`. It's worse than the current one imo because `typing` types aliases are quite common in my experience. – Arne Aug 07 '19 at 11:37
  • 4
    That's not what I meant. `inspect.signature()` will give you a `Signature` instance which will let you trivially create a set of acceptable parameter names. – Martijn Pieters Aug 07 '19 at 12:40
  • I wasn't aware of `inspect.signature()`, thanks for the hint. The version right now seems to just work for all my test cases, and it gets rid of all the private attribute/function accesses. – Arne Aug 07 '19 at 13:13
  • I've applied this to my metaclass in the [other post](https://stackoverflow.com/questions/57357818/how-can-i-fix-the-typeerror-of-my-dataclass-in-python); it is a little more complex than just verifying that the argument exists as there may be positional-only arguments. – Martijn Pieters Aug 07 '19 at 13:14
  • If performance is a concern, it's much faster to check directly `cls.__dataclass_fields__`. Performance can be improved also by assigning `inspect.signature(cls).parameters` to a variable outside the dictionary comprehension. – tboschi Sep 02 '21 at 17:08
  • @tboschi see [revision 5](https://stackoverflow.com/revisions/55096964/5) of my post, it's not easy to get right. You're right about the condition into a variable though. – Arne Sep 02 '21 at 19:50
  • @Arne ah sweet, thanks for linking your revision! – tboschi Sep 02 '21 at 23:48
31

I would just provide an explicit __init__ instead of using the autogenerated one. The body of the loop only sets recognized value, ignoring unexpected ones.

Note that this won't complain about missing values without defaults until later, though.

@dataclass(init=False)
class Config:
    VAR_NAME_1: str
    VAR_NAME_2: str

    def __init__(self, **kwargs):
        names = set([f.name for f in dataclasses.fields(self)])
        for k, v in kwargs.items():
            if k in names:
                setattr(self, k, v)

Alternatively, you can pass a filtered environment to the default Config.__init__.

field_names = set(f.name for f in dataclasses.fields(Config))
c = Config(**{k:v for k,v in os.environ.items() if k in field_names})
smcjones
  • 5,490
  • 1
  • 23
  • 39
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Yeah that was my concern, it looked like the function was a little more complicated with some checks etc (but I only looked for a second). Is there any way to just rip out the autogenerated function and wrap it? I also don't really want the other environment variables in there. – Californian Feb 13 '19 at 21:10
  • 2
    You don't want to wrap the autogenerated function; you want to replace it. That said, you can always filter the environment mapping *before* calling the default `__init__`: `c = Config({k:v for k,v in kwargs if k in set(f.name for f in dataclasses.fields(Config))})` – chepner Feb 13 '19 at 21:19
  • 2
    Filtering the arguments before initializing the instance worked great! If you make that into a separate answer I'll accept it. Code I ended up with: `from dataclasses import dataclass, fields` ... `config = Config(**{k:v for k,v in os.environ.items() if k in set(f.name for f in fields(Config))}`. – Californian Feb 14 '19 at 20:50
  • Following "favor composition over inheritance" you may want iterative calls to this as a helper function (e.g., when pulling an already joined query that might be a pain to splice) to properly separate base dataclasses. – Elysiumplain May 06 '22 at 20:55
  • 1
    you are losing all of the magic that dataclass is doing in '__init__'. This is not a solution to this problem! – jonathan May 31 '22 at 02:48
7

I used a combination of both answers; setattr can be a performance killer. Naturally, if the dictionary won't have some records in the dataclass, you'll need to set field defaults for them.

from __future__ import annotations
from dataclasses import field, fields, dataclass

@dataclass()
class Record:
    name: str
    address: str
    zip: str = field(default=None)  # won't fail if dictionary doesn't have a zip key

    @classmethod
    def create_from_dict(cls, dict_) -> Record:
        class_fields = {f.name for f in fields(cls)}
        return Record(**{k: v for k, v in dict_.items() if k in class_fields})
anttilip
  • 3
  • 2
Doug
  • 3,472
  • 3
  • 21
  • 18
2

Using the dacite python library to populate a dataclass using a dictionary of values ignores extra arguments / values present in the dictionary (along with all the other benefits the library provides).

from dataclasses import dataclass
from dacite import from_dict


@dataclass
class User:
    name: str
    age: int
    is_active: bool


data = {
    'name': 'John',
    'age': 30,
    'is_active': True,
    "extra_1": 1000,
    "extra_2": "some value"
}

user = from_dict(data_class=User, data=data)
print(user)
# prints the following: User(name='John', age=30, is_active=True)
0

I did this based on previous answers:

import functools
import inspect

@functools.cache
def get_dataclass_parameters(cls: type):
    return inspect.signature(cls).parameters


def instantiate_dataclass_from_dict(cls: type, dic: dict):
    parameters = get_dataclass_parameters(cls)
    dic = {k: v for k, v in dic.items() if k in parameters}
    return cls(**dic)

Since inspect.signature(cls).parameters takes much more time than the actual instantiation / initialization, I use functools.cache to cache the result for each class.

Frozen Flame
  • 3,135
  • 2
  • 23
  • 35