5

I am trying to get used with new python's features (dataclasses). I am trying to initialize variables and I get error:

raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'dict'> for field headers is not allowed: use default_factory

My code:

@dataclass
class Application():
    __config = ConfigParser()
    __config.read('mydb.ini')
    __host: str = __config.get('db','dbhost')
    __user: str = __config.get('db','dbuser')
    __password: str = __config.get('db','dbpw')
    __database: str = __config.get('db','database')
    url: str = "https://xxxx.domain.com/"
    headers: str = {'X-ApiKeys':'accessKey=xxxxxxx;secretKey=xxxxx','Content-Type': 'application/json'}



def main(self):
    print(self.__host,self.__user,self.__password, self.__database)
   


app = Application()
if __name__=="__main__":
    app.main()

What's the proper way to initialize dictionaries?

robotiaga
  • 315
  • 2
  • 11
  • Does this answer your question? [Why can't dataclasses have mutable defaults in their class attributes declaration?](https://stackoverflow.com/questions/53632152/why-cant-dataclasses-have-mutable-defaults-in-their-class-attributes-declaratio) – Epic Wink Sep 13 '22 at 05:05

1 Answers1

8

Dataclasses have a few useful things for defining complex fields. The one that you need is called field. This one has the argument default_factory that needs to receive callable, and there is where lambda comes to the rescue. So using this above, code that will work looks like (just part with dict):

from dataclasses import field
from typing import Dict

@dataclass
class Application():
    ...
    headers: Dict[str, str] = field(
        default_factory=lambda: {'X-ApiKeys':'accessKey=xxxxxxx;secretKey=xxxxx','Content-Type': 'application/json'}
    )