namedtuple

Mapping result rows to namedtuple in python sqlite

假如想象 提交于 2019-12-30 03:04:06
问题 I am playing a bit with the python api for sqlite3, i have a little table for store languages with an id, name and creation_date fields. I am trying to map the raw query results into a namedtuple as the docs recommend, it that way i can manage rows in a more readable way, so here is my namedtuple . LanguageRecord = namedtuple('LanguageRecord', 'id, name, creation_date') The code that the docs suggest for the mapping is as follows: for language in map(LanguageRecord._make, c.fetchall()): # do

How to use namedtuples in multiple inheritance

与世无争的帅哥 提交于 2019-12-29 08:23:06
问题 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

Python put Database records in Namedtuple

不想你离开。 提交于 2019-12-25 01:45:10
问题 I'm trying to write some code in python (2.7) doing this: Open a database in sqlite Do a query to the database, getting some results. The database has more than one table and i need the records from different tables: database is like this: data.db ---> [table1[col1, col2, col3], table2[col1, col2, col3]] Iterate through the results Do something on the results (for exaple in a record there is a date that need decoding) Store all the records in a namedtuple for further access Since now i have

Why does namedtuple in python need a name?

落爺英雄遲暮 提交于 2019-12-24 08:23:35
问题 Why do we need to mention the name Card for namedtuple like below? import collections Card = collections.namedtuple('Card', ['rank', 'suit']) I think a simple Card = collections.namedtuple(['rank', 'suit']) can actually give the same effect right? For example I can have the same information in a dict like: card = dict({'rank': 'A', 'suit': 'spade'}) 回答1: No, that won't give the same effect. collections.namedtuple : Returns a new tuple subclass named typename... namedtuple returns a subclass

Writing and reading namedtuple into a file in python

寵の児 提交于 2019-12-24 02:45:28
问题 I need to write a data structure stored as namedtuple to file and read it back as a namedtuple in python. Solutions here suggest using Json.load / loads or pickle which write the variable as json key-value pair in the form of strings. However, all my field accesses/dereferences are of the form struct.key (rather than struct["key"] which is the way to access json values), and it is unfeasible to correct this in the whole code. I want to store this to a file because the struct is huge and takes

Namedtuple error [closed]

孤人 提交于 2019-12-24 01:44:47
问题 Closed. This question is off-topic. It is not currently accepting answers. Want to improve this question? Update the question so it's on-topic for Stack Overflow. Closed 5 years ago . I am trying to serialize a Python object into JSON using namedtuple. But I get this error. Google does not help. Traceback (most recent call last): File "cpu2.py", line 28, in <module> cpuInfo = collections.namedtuple('cpuStats',('cpu.usr', ('str(currentTime) + " " +str(cpuStats[0]) + " host="+ thisClient')), (

Namedtuple vs Dictionary

 ̄綄美尐妖づ 提交于 2019-12-24 01:16:00
问题 So I'm programming a game and I need a datatype that can store a multitude of variables ranging from lists , tuples , strings and integers . I'm torn between using either dictionaries or namedtuples . GameData = namedtuple('GameData', ['Stats', 'Inventory', 'Name', 'Health']) current_game = GameData((20,10,55,3), ['Sword', 'Apple', 'Potion'], 'Arthur', 100) GameData = {'Stats': (20,10,55,3), 'Inventory': ['Sword', 'Apple', 'Potion'], 'Name': 'Arthur', 'Health': 100} You see, the biggest

Any way to bypass namedtuple 255 arguments limitation?

拜拜、爱过 提交于 2019-12-22 18:18:40
问题 I'm using a namedtuple to hold sets of strings and their corresponding values. I'm not using a dictionary, because I want the strings accessible as attributes. Here's my code: from collections import namedtuple # Shortened for readability :-) strings = namedtuple("strings", ['a0', 'a1', 'a2', ..., 'a400']) my_strings = strings(value0, value1, value2, ..., value400) Ideally, once my_strings is initialized, I should be able to do this: print(my_strings.a1) and get value1 printed back. However ,

Harmful side effects for different namedtuples with same typename?

不想你离开。 提交于 2019-12-22 10:18:40
问题 Consider the following function: >>> from collections import namedtuple >>> def make_thing(**kwargs): ... ThingClass = namedtuple('ThingClass', kwargs.keys()) ... return ThingClass(**kwargs) ... >>> make_thing(x=1,y=2,z=3) ThingClass(y=2, x=1, z=3) >>> make_thing(a=4,b=5,c=6) ThingClass(a=4, c=6, b=5) >>> The function calls namedtuple to produce a "temporary" class with field names the same as the input dict 's keys. Then it returns an instance with the values filled in. My question is

cannot init an instance of a subclassed namedtuple

耗尽温柔 提交于 2019-12-22 08:18:22
问题 I think I have not undertood how to define a class subclassed from a namedtuple : from collections import namedtuple PD = namedtuple('PD', 'x y z') p1 = PD(0, 'u', 1) print p1.x #<== this works class PDsub(PD): __slots__ = () def __new__(cls, x, y, z): self = super(PDsub, cls).__new__(cls, x, y, z) return self def __init__(self, a): self.x, self.y, self.z = a, a, a def __str__(self): return 'Foo' p2 = PDsub(5) #<== this does not work This code raises TypeError : __new__() takes exactly 4