Weird MRO result when inheriting directly from typing.NamedTuple

This is because typing.NamedTuple is not really a proper type. It is a class. But its singular purpose is to take advantage of meta-class magic to give you a convenient nice way to define named-tuple types. And named-tuples derive from tuple directly. Note, unlike most other classes, from typing import NamedTuple class Foo(NamedTuple): pass print(isinstance(Foo(), … 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

How to pickle a namedtuple instance correctly

Create the named tuple outside of the function: from collections import namedtuple import pickle P = namedtuple(“P”, “one two three four”) def pickle_test(): my_list = [] abe = P(“abraham”, “lincoln”, “vampire”, “hunter”) my_list.append(abe) with open(‘abe.pickle’, ‘wb’) as f: pickle.dump(abe, f) pickle_test() Now pickle can find it; it is a module global now. When unpickling, all … 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

A way to subclass NamedTuple for purposes of typechecking

The way named tuples are constructed make inheritance from typing.NamedTuple classes as yet not possible. You’d have to write your own metaclass to extend the typing.NamedTupleMeta class to make subclassing work, and even then the class generated by collections.namedtuple() is just not built to extend. Instead, you want to use the new dataclasses module to … Read more