Adding docstrings to namedtuples?

In Python 3, no wrapper is needed, as the __doc__ attributes of types is writable. from collections import namedtuple Point = namedtuple(‘Point’, ‘x y’) Point.__doc__ = ”’\ A 2-dimensional coordinate x – the abscissa y – the ordinate”’ This closely corresponds to a standard class definition, where the docstring follows the header. class Point(): ”’A … Read more

Pythonic way to convert a dictionary into namedtuple or another hashable dict-like?

To create the subclass, you may just pass the keys of a dict directly: MyTuple = namedtuple(‘MyTuple’, d) Now to create tuple instances from this dict, or any other dict with matching keys: my_tuple = MyTuple(**d) Beware: namedtuples compare on values only (ordered). They are designed to be a drop-in replacement for regular tuples, with … Read more

Serializing a Python namedtuple to json

If it’s just one namedtuple you’re looking to serialize, using its _asdict() method will work (with Python >= 2.7) >>> from collections import namedtuple >>> import json >>> FB = namedtuple(“FB”, (“foo”, “bar”)) >>> fb = FB(123, 456) >>> json.dumps(fb._asdict()) ‘{“foo”: 123, “bar”: 456}’

Existence of mutable named tuple in Python?

There is a mutable alternative to collections.namedtuple – recordclass. It can be installed from PyPI: pip3 install recordclass It has the same API and memory footprint as namedtuple and it supports assignments (It should be faster as well). For example: from recordclass import recordclass Point = recordclass(‘Point’, ‘x y’) >>> p = Point(1, 2) >>> … 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

Convert a namedtuple into a dictionary

TL;DR: there’s a method _asdict provided for this. Here is a demonstration of the usage: >>> fields = [‘name’, ‘population’, ‘coordinates’, ‘capital’, ‘state_bird’] >>> Town = collections.namedtuple(‘Town’, fields) >>> funkytown = Town(‘funky’, 300, ‘somewhere’, ‘lipps’, ‘chicken’) >>> funkytown._asdict() OrderedDict([(‘name’, ‘funky’), (‘population’, 300), (‘coordinates’, ‘somewhere’), (‘capital’, ‘lipps’), (‘state_bird’, ‘chicken’)]) This is a documented method of namedtuples, … Read more

Named tuple and default values for optional keyword arguments

Python 3.7 Use the defaults parameter. >>> from collections import namedtuple >>> fields = (‘val’, ‘left’, ‘right’) >>> Node = namedtuple(‘Node’, fields, defaults=(None,) * len(fields)) >>> Node() Node(val=None, left=None, right=None) Or better yet, use the new dataclasses library, which is much nicer than namedtuple. >>> from dataclasses import dataclass >>> from typing import Any >>> … Read more

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