namedtuple

Subclassing Python namedtuple

早过忘川 提交于 2019-11-30 13:15:13
问题 Python's namedtuple can be really useful as a lightweight, immutable data class. I like using them for bookkeeping parameters rather than dictionaries. When some more functionality is desired, such as a simple docstring or default values, you can easily refactor the namedtuple to a class. However, I've seen classes that inherit from namedtuple. What functionality are they gaining, and what performance are they losing? For example, I would implement this as from collections import namedtuple

Relevance of typename in namedtuple

╄→尐↘猪︶ㄣ 提交于 2019-11-30 10:50:08
from collections import namedtuple Point=namedtupe('whatsmypurpose',['x','y']) p=Point(11,22) print(p) Output: whatsmypurpose(x=11,y=22) What's the relevance/use of 'whatsmypurpose' ? haraprasadj 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'], verbose=True) Also you can try type(p) to verify this. 'whatsmypurpose' gives the new subclass its type

How to use namedtuples in multiple inheritance

喜欢而已 提交于 2019-11-29 12:46:42
Is it possible to create a class that inherits from multiple instances of namedtuple , or create something to the same effect (having an immutable type that combines the fields of the base types)? I haven't found a way to do so. This example illustrates the problem: >>> class Test(namedtuple('One', 'foo'), namedtuple('Two', 'bar')): >>> pass >>> t = Test(1, 2) TypeError: __new__() takes 2 positional arguments but 3 were given >>> t = Test(1) >>> t.foo 1 >>> t.bar 1 The problem seems to be that namedtuple does not use super to initialize its base class, as can be seen when creating one: >>>

Python: Extending a predefined named tuple

拥有回忆 提交于 2019-11-28 23:16:10
I have the following named tuple: from collections import namedtuple ReadElement = namedtuple('ReadElement', 'address value') and then I want the following: LookupElement = namedtuple('LookupElement', 'address value lookups') There is duplication between the two namedtuples, how can I subclass ReadElement to contain an additional field? class LookupElement(ReadElement): def __new__(self, address, value, lookups): self = super(LookupElement, self).__new__(address, value) l = list(self) l.append(lookups) return tuple(l) However the tuple is created there an then in the new statement, if I modify

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

让人想犯罪 __ 提交于 2019-11-28 21:07:48
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 TypeError . What is the pythonic way to reader a file header into a namedtuple? Use: Data = namedtuple(

Pythonic Way to Convert Dictionary to namedtuple, or Another Hashable dict-like?

混江龙づ霸主 提交于 2019-11-28 19:42:05
问题 I have a dictionary like: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} which I would like to convert to a namedtuple. My current approach is with the following code namedTupleConstructor = namedtuple('myNamedTuple', ' '.join(sorted(d.keys()))) nt= namedTupleConstructor(**d) which produces myNamedTuple(a=1, b=2, c=3, d=4) This works fine for me (I think), but am I missing a built-in such as... nt = namedtuple.from_dict() ? UPDATE: as discussed in the comments, my reason for wanting to convert my

Pythonic way to sorting list of namedtuples by field name

情到浓时终转凉″ 提交于 2019-11-28 18:33:14
I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution. from operator import itemgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [ Person(name='nick', age=23, score=100), Person(name='bob', age=25, score=200), ] # sort list by name print(sorted(seq, key=itemgetter(Person._fields.index('name')))) # sort list by age print(sorted(seq, key=itemgetter(Person._fields.index('age')))) Thanks, Nick from operator import

python Named tuple to dictionary

有些话、适合烂在心里 提交于 2019-11-28 17:41:19
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 elses code. So I need to take an instance of a Town and convert it to a dictionary. TL;DR: there's a

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

99封情书 提交于 2019-11-28 17:11:12
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 poll. Edit: I need to iterate through the object displaying its attributes using PyQt. I know I can add

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

痞子三分冷 提交于 2019-11-28 15:15:26
I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should the class inherit from namedtuple instead? Edit: If you have python 3.7+ just use dataclasses A decorator solution that keeps the signature: import decorator import inspect import sys @decorator.decorator def simple_init(func, self, *args, **kws): """ @simple_init def __init__(self,a,b,...,z) dosomething() behaves like def __init__(self,a,b,...,z) self.a = a self.b = b ... self.z =