Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing default list argument to dataclasses

I would like to pass default argument in my class, but somehow I am having problem:

from dataclasses import dataclass, field from typing import List  @dataclass class Pizza():     ingredients: List = field(default_factory=['dow', 'tomatoes'])     meat: str = field(default='chicken')      def __repr__(self):         return 'preparing_following_pizza {} {}'.format(self.ingredients, self.meat) 

If I now try to instantiate Pizza, I get the following error:

>>> my_order = Pizza() Traceback (most recent call last):   File "pizza.py", line 13, in <module>     Pizza()   File "<string>", line 2, in __init__ TypeError: 'list' object is not callable 

What am I doing wrong?

like image 224
H.Bukhari Avatar asked Aug 28 '18 17:08

H.Bukhari


People also ask

Can Dataclasses have methods?

A dataclass can very well have regular instance and class methods. Dataclasses were introduced from Python version 3.7. For Python versions below 3.7, it has to be installed as a library.

What is __ Post_init __?

The __post_init__ method is called just after initialization. In other words, it is called after the object receives values for its fields, such as name , continent , population , and official_lang .

What does @dataclass do in Python?

dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation. Although the module was introduced in Python3.

What is Dataclass?

A data class is a class typically containing mainly data, although there aren't really any restrictions. It is created using the new @dataclass decorator, as follows: from dataclasses import dataclass @dataclass class DataClassCard: rank: str suit: str.


1 Answers

From the dataclasses.field docs:

The parameters to field() are:

  • default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory.

Your default_factory is not a 0-argument callable but a list, which is the reason for the error:

from dataclasses import dataclass, field from typing import List  @dataclass class Pizza():     ingredients: List = field(default_factory=['dow', 'tomatoes'])  # <- wrong! 

Use a lambda function instead:

@dataclass class Pizza():     ingredients: List = field(default_factory=lambda: ['dow', 'tomatoes']) 
like image 118
Aran-Fey Avatar answered Sep 19 '22 14:09

Aran-Fey