python-dataclasses

Python dataclass from a nested dict

青春壹個敷衍的年華 提交于 2019-12-20 08:36:54
问题 The standard library in 3.7 can recursively convert a dataclass into a dict (example from the docs): from dataclasses import dataclass, asdict from typing import List @dataclass class Point: x: int y: int @dataclass class C: mylist: List[Point] p = Point(10, 20) assert asdict(p) == {'x': 10, 'y': 20} c = C([Point(0, 0), Point(10, 4)]) tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} assert asdict(c) == tmp I am looking for a way to turn a dict back into a dataclass when there is

Easiest way to copy all fields from one Python dataclass instance to another instance

别来无恙 提交于 2019-12-20 03:06:24
问题 Let's assume you have defined a Python dataclass: @dataclass class Marker: a: float b: float = 1.0 What's the easiest way to copy the values from an instance marker_a to another instance marker_b ? Here's an example of what I try to achieve: marker_a = Marker(1.0, 2.0) marker_b = Marker(11.0, 12.0) # now some magic happens which you hopefully can fill in print(marker_b) # result: Marker(a=1.0, b=2.0) As a boundary condition, I don't want to create and assign a new instance to marker_b . Ok, I

How to add a dataclass field without annotating the type?

半世苍凉 提交于 2019-12-19 14:58:31
问题 When there is a field in a dataclass for which the type can be anything, how can you omit the annotation? @dataclass class Favs: fav_number: int = 80085 fav_duck = object() fav_word: str = 'potato' It seems the code above doesn't actually create a field for fav_duck . It just makes that a plain old class attribute. >>> Favs() Favs(fav_number=80085, fav_word='potato') >>> print(*Favs.__dataclass_fields__) fav_number fav_word >>> Favs.fav_duck <object at 0x7fffea519850> 回答1: The dataclass

Using dataclasses with dependent attributes via property

元气小坏坏 提交于 2019-12-19 04:18:32
问题 I have a class, for example Circle , which has dependent attributes, radius and circumference . It makes sense to use a dataclass here because of the boilerplate for __init__ , __eq__ , __repr__ and the ordering methods ( __lt__ , ...). I choose one of the attributes to be dependent on the other, e.g. the circumference is computed from the radius. Since the class should support initialization with either of the attributes (+ have them included in __repr__ as well as dataclasses.asdict ) I

What are data classes and how are they different from common classes?

江枫思渺然 提交于 2019-12-17 07:02:42
问题 With PEP 557 data classes are introduced into python standard library. They make use of the @dataclass decorator and they are supposed to be "mutable namedtuples with default" but I'm not really sure I understand what this actually means and how they are different from common classes. What exactly are python data classes and when is it best to use them? 回答1: Data classes are just regular classes that are geared towards storing state, more than contain a lot of logic. Every time you create a

How to use dataclasses to generate a field value?

Deadly 提交于 2019-12-12 13:08:43
问题 I have the following class: class WordItem: def __init__(self, phrase: str, word_type: WORD_TYPE): self.id = f'{phrase}_{word_type.name.lower()}' self.phrase = phrase self.word_type = word_type @classmethod def from_payload(cls, payload: Dict[str, Any]) -> 'WordItem': return cls(**payload) How can I rewrite this class as a dataclass? Specifically, how should the id field be declared? It has a generated value, and is not a field that the code creating instances would provide. 回答1: Just move

python3 dataclass with **kwargs(asterisk)

断了今生、忘了曾经 提交于 2019-12-11 05:13:34
问题 Currently I used DTO(Data Transfer Object) like this. class Test1: def __init__(self, user_id: int = None, body: str = None): self.user_id = user_id self.body = body Example code is very small, But when object scale growing up, I have to define every variable. While digging into it, found that python 3.7 supported dataclass Below code is DTO used dataclass. from dataclasses import dataclass @dataclass class Test2: user_id: int body: str In this case, How can I allow pass more argument that

How can I fix the TypeError of my dataclass in Python?

有些话、适合烂在心里 提交于 2019-12-11 01:13:28
问题 I have a dataclass with 5 attributes. When I give these attributes via a dictionary, it works well. But when the dictionary has more attributes than the class have, the class gives TypeError. I am trying to make that when there is extra values, the class wouldn't care them. How can I make that? from dataclasses import dataclass @dataclass class Employee(object): name: str lastname: str age: int or None salary: int department: str def __new__(cls, name, lastname, age, salary, department):

How does one ignore extra arguments passed to a data class?

怎甘沉沦 提交于 2019-12-10 12:48:26
问题 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

How can I get Python 3.7 new dataclass field types?

社会主义新天地 提交于 2019-12-08 14:34:17
问题 Python 3.7 introduces new feature called data classes. from dataclasses import dataclass @dataclass class MyClass: id: int = 0 name: str = '' When using type hints (annotation) in function parameters, you can easily get annotated types using inspect module. How can I get dataclass field types? 回答1: from dataclasses import dataclass @dataclass class MyClass: id: int = 0 name: str = '' myclass = MyClass() myclass.__annotations__ >> {'id': int, 'name': str} myclass.__dataclass_fields__ >> {'id':