namedtuple

A way to subclass NamedTuple for purposes of typechecking

主宰稳场 提交于 2019-11-28 12:03:15
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_extended) When I run mypy on this code I get a predictable error: mypy_example.py:20: error: Argument 1

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

柔情痞子 提交于 2019-11-28 07:13:25
How do I check if an object is an instance of a Named tuple ? Alex Martelli 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 all(type(n)==str for n in f) it IS possible to get a false positive from this, but only if

How to pickle a namedtuple instance correctly

可紊 提交于 2019-11-28 06:43:33
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(): P = namedtuple("P", "one two three four") my_list = [] abe = P("abraham", "lincoln", "vampire",

What does *tuple and **dict means in Python? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-11-28 06:30:28
This question already has an answer here: What do *args and **kwargs mean? [duplicate] 5 answers As mentioned in PythonCookbook, * can be added before a tuple, and what does * mean here? Chapter 1.18. Mapping Names to Sequence Elements: from collections import namedtuple Stock = namedtuple('Stock', ['name', 'shares', 'price']) s = Stock(*rec) # here rec is an ordinary tuple, for example: rec = ('ACME', 100, 123.45) In the same section, **dict presents: from collections import namedtuple Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time']) # Create a prototype instance stock

Adding docstrings to namedtuples?

守給你的承諾、 提交于 2019-11-28 04:36:47
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? Mark Rushakoff You can achieve this by creating a simple, empty wrapper class around the returned value from namedtuple . Contents of a file I created ( nt.py ): from

Type hints in namedtuple

穿精又带淫゛_ 提交于 2019-11-27 19:33:58
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? Wolfgang Kuehn 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

Relevance of typename in namedtuple

五迷三道 提交于 2019-11-27 17:10:38
问题 from collections import namedtuple Point = namedtuple('whatsmypurpose',['x','y']) p = Point(11,22) print(p) Output: whatsmypurpose(x=11,y=22) What's the relevance/use of 'whatsmypurpose' ? 回答1: namedtuple() is a factory function for tuple subclasses. Here, 'whatsmypurpose' is the type name. When you create a named tuple, a class with this name ( whatsmypurpose ) gets created internally. You can notice this by using the verbose argument like: Point=namedtuple('whatsmypurpose',['x','y'],

Existence of mutable named tuple in Python?

对着背影说爱祢 提交于 2019-11-27 17:00:54
Can anyone amend namedtuple or provide an alternative class so that it works for mutable objects? Primarily for readability, I would like something similar to namedtuple that does this: from Camelot import namedgroup Point = namedgroup('Point', ['x', 'y']) p = Point(0, 0) p.x = 10 >>> p Point(x=10, y=0) >>> p.x *= 10 Point(x=100, y=0) It must be possible to pickle the resulting object. And per the characteristics of named tuple, the ordering of the output when represented must match the order of the parameter list when constructing the object. There is a mutable alternative to collections

What is the pythonic way to read CSV file data as rows of namedtuples?

会有一股神秘感。 提交于 2019-11-27 13:30:04
问题 What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reader(infile) Data = namedtuple("Data", ", ".join(i for i in reader[0])) next(reader) for row in reader: data = Data(*row) The reader object is not subscriptable, so the above code throws a

python Named tuple to dictionary

ぃ、小莉子 提交于 2019-11-27 10:54:47
问题 I have a named tuple class in python class Town(collections.namedtuple('Town', [ 'name', 'population', 'coordinates', 'population', 'capital', 'state_bird'])): # ... I'd like to convert Town instances into dictionaries. I dont want it to be rigidly tied to the names or number of the fields in a Town. Is there a way to write it such that I could add more fields, or pass an entirely different named tuple in and get a dictionary. I can not alter the original class definition as its in someone