Make the Python json encoder support Python’s new dataclasses

Much like you can add support to the JSON encoder for datetime objects or Decimals, you can also provide a custom encoder subclass to serialize dataclasses: import dataclasses, json class EnhancedJSONEncoder(json.JSONEncoder): def default(self, o): if dataclasses.is_dataclass(o): return dataclasses.asdict(o) return super().default(o) json.dumps(foo, cls=EnhancedJSONEncoder)

Python dataclass from a nested dict

I’m the author of dacite – the tool that simplifies creation of data classes from dictionaries. This library has only one function from_dict – this is a quick example of usage: from dataclasses import dataclass from dacite import from_dict @dataclass class User: name: str age: int is_active: bool data = { ‘name’: ‘john’, ‘age’: 30, … Read more

How do I avoid the “self.x = x; self.y = y; self.z = z” pattern in __init__?

Disclaimer: It seems that several people are concerned about presenting this solution, so I will provide a very clear disclaimer. You should not use this solution. I only provide it as information, so you know that the language is capable of this. The rest of the answer is just showing language capabilities, not endorsing using … Read more

Data Classes vs typing.NamedTuple primary use cases

It depends on your needs. Each of them has own benefits. Here is a good explanation of Dataclasses on PyCon 2018 Raymond Hettinger – Dataclasses: The code generator to end all code generators In Dataclass all implementation is written in Python, whereas in NamedTuple, all of these behaviors come for free because NamedTuple inherits from … Read more

Type hints in namedtuple

The prefered Syntax for a typed named tuple since 3.6 is from typing import NamedTuple class Point(NamedTuple): x: int y: int = 1 # Set default value Point(3) # -> Point(x=3, y=1) Edit Starting Python 3.7, consider using dataclasses (your IDE may not yet support them for static type checking): from dataclasses import dataclass @dataclass … Read more

Class inheritance in Python 3.7 dataclasses

The way dataclasses combines attributes prevents you from being able to use attributes with defaults in a base class and then use attributes without a default (positional attributes) in a subclass. That’s because the attributes are combined by starting from the bottom of the MRO, and building up an ordered list of the attributes in … Read more

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

Data classes are just regular classes that are geared towards storing state, rather than containing a lot of logic. Every time you create a class that mostly consists of attributes, you make a data class. What the dataclasses module does is to make it easier to create data classes. It takes care of a lot … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)