ValueError: mutable default <class 'dict'> for field headers is not allowed: use default_factory

Viewed 885

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?

1 Answers

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'}
    )
Related