namedtuple

Why does Python not support record type? (i.e. mutable namedtuple)

本秂侑毒 提交于 2019-11-27 10:07:00
问题 Why does Python not support a record type natively? It's a matter of having a mutable version of namedtuple. I could use namedtuple._replace . But I need to have these records in a collection and since namedtuple._replace creates another instance, I also need to modify the collection which becomes messy quickly. Background: I have a device whose attributes I need to get by polling it over TCP/IP. i.e. its representation is a mutable object. Edit: I have a set of devices for whom I need to

Serializing a Python namedtuple to json

非 Y 不嫁゛ 提交于 2019-11-27 06:39:32
What is the recommended way of serializing a namedtuple to json with the field names retained? Serializing a namedtuple to json results in only the values being serialized and the field names being lost in translation. I would like the fields also to be retained when json-ized and hence did the following: class foobar(namedtuple('f', 'foo, bar')): __slots__ = () def __iter__(self): yield self._asdict() The above serializes to json as I expect and behaves as namedtuple in other places I use (attribute access etc.,) except with a non-tuple like results while iterating it (which fine for my use

namedtuple and default values for optional keyword arguments

喜你入骨 提交于 2019-11-27 05:47:51
I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this: class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right After conversion to namedtuple it looks like: from collections import namedtuple Node = namedtuple('Node', 'val left right') But there is a problem here. My original class allowed me to pass in just a value and took care of the default by using default values for the named/keyword arguments. Something like: class BinaryTree(object): def __init__(self, val): self.root =

Adding docstrings to namedtuples?

空扰寡人 提交于 2019-11-27 05:23:44
问题 Is it possible to add a documentation string to a namedtuple in an easy manner? I tried from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D space """ Point2 = namedtuple("Point2", ["x", "y"]) print Point.__doc__ # -> "Point(x, y)" print Point2.__doc__ # -> "Point2(x, y)" but that doesn't cut it. Is it possible to do in some other way? 回答1: You can achieve this by creating a simple, empty wrapper

A way to subclass NamedTuple for purposes of typechecking

霸气de小男生 提交于 2019-11-27 03:55:23
问题 I have several namedtuples that share some fields. I have a function that accepts these tuples and is guaranteed to only interact with the shared fields. I want to typecheck such code in mypy. An example of the code would be: from typing import NamedTuple class Base(NamedTuple): x: int y: int class BaseExtended(NamedTuple): x: int y: int z: str def DoSomething(tuple: Base): return tuple.x + tuple.y base = Base(3, 4) base_extended = BaseExtended(5, 6, 'foo') DoSomething(base) DoSomething(base

How to check if an object is an instance of a namedtuple?

試著忘記壹切 提交于 2019-11-27 01:34:36
问题 How do I check if an object is an instance of a Named tuple? 回答1: Calling the function collections.namedtuple gives you a new type that's a subclass of tuple (and no other classes) with a member named _fields that's a tuple whose items are all strings. So you could check for each and every one of these things: def isnamedtupleinstance(x): t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return

How to pickle a namedtuple instance correctly

孤者浪人 提交于 2019-11-27 01:27:20
问题 I'm learning how to use pickle. I've created a namedtuple object, appended it to a list, and tried to pickle that list. However, I get the following error: pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P I found that if I ran the code without wrapping it inside a function, it works perfectly. Is there an extra step required to pickle an object when wrapped inside a function? Here is my code: from collections import namedtuple import pickle def pickle_test

Type hints in namedtuple

无人久伴 提交于 2019-11-26 19:47:22
问题 Consider following piece of code: from collections import namedtuple point = namedtuple("Point", ("x:int", "y:int")) The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuple with type hints. Do you know any elegant way how to achieve result as intended? 回答1: 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

namedtuple and default values for optional keyword arguments

人盡茶涼 提交于 2019-11-26 10:05:50
问题 I\'m trying to convert a longish hollow \"data\" class into a named tuple. My class currently looks like this: class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right After conversion to namedtuple it looks like: from collections import namedtuple Node = namedtuple(\'Node\', \'val left right\') But there is a problem here. My original class allowed me to pass in just a value and took care of the default by using default values for

What are “named tuples” in Python?

二次信任 提交于 2019-11-25 23:15:05
问题 Reading the changes in Python 3.1, I found something... unexpected: The sys.version_info tuple is now a named tuple : I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in tuples and lists) or by keys (like in dicts). I never expected they could be indexed both ways. Thus, my questions are: What are named tuples? How to use them? Why/when should I use named tuples instead of normal tuples? Why/when should I use normal tuples instead of