namedtuple

Why doesn't the namedtuple module use a metaclass to create nt class objects?

不想你离开。 提交于 2019-12-22 01:34:22
问题 I spent some time investigating the collections.namedtuple module a few weeks ago. The module uses a factory function which populates the dynamic data (the name of the new namedtuple class, and the class attribute names) into a very large string. Then exec is executed with the string (which represents the code) as the argument, and the new class is returned. Does anyone know why it was done this way, when there is a specific tool for this kind of thing readily available, i.e. the metaclass? I

How to convert a pandas dataframe to namedtuple

China☆狼群 提交于 2019-12-20 05:48:07
问题 How to convert a pandas dataframe to namedtuple? This task is going towards multiprocessing work. def df2namedtuple(df): return tuple(df.row) 回答1: itertuples has option name and index . You may use them to return exact output as your posted function: sample df: df: A B C D 0 32 70 39 66 1 89 30 31 80 2 21 5 74 63 list(df.itertuples(name='Row', index=False)) Out[1130]: [Row(A=32, B=70, C=39, D=66), Row(A=89, B=30, C=31, D=80), Row(A=21, B=5, C=74, D=63)] 回答2: Answer from Dan in https://groups

Dictionary With Lambda Values Updates All Entries

百般思念 提交于 2019-12-20 03:07:35
问题 I'm in Python 2.7. I have two classes and one namedtuple. One class houses a dictionary as an instance attribute and a function that assigns to that dictionary. (This is a very simplified version of the situation). The namedtuple is simple enough. The other class is one that adds entries into test_dict via the add_to_test_dict function call. Then I instantiate DictManipulator and call the test function: from collections import namedtuple class DictHolder(object): def __init__(self): self.test

Creating a namedtuple object using only a subset of arguments passed

我是研究僧i 提交于 2019-12-19 10:26:18
问题 I am pulling rows from a MySQL database as dictionaries (using SSDictCursor) and doing some processing, using the following approach: from collections import namedtuple class Foo(namedtuple('Foo', ['id', 'name', 'age'])): __slots__ = () def __init__(self, *args): super(Foo, self).__init__(self, *args) # ...some class methods below here class Bar(namedtuple('Bar', ['id', 'address', 'city', 'state']): __slots__ = () def __init__(self, *args): super(Bar, self).__init__(self, *args) # some class

How named tuples are implemented internally in python?

女生的网名这么多〃 提交于 2019-12-18 19:27:44
问题 Named tuples are easy to create, lightweight object types. namedtuple instances can be referenced using object-like variable deferencing or the standard tuple syntax. If these data structures can be accessed both by object deferencing & indexes, how are they implemented internally? Is it via hash tables? 回答1: Actually, it's very easy to find out how a given namedtuple is implemented: if you pass the keyword argument verbose=True when creating it, its class definition is printed: >>> Point =

How to access a field of a namedtuple using a variable for the field name?

纵饮孤独 提交于 2019-12-18 13:53:16
问题 I can access elements of a named tuple by name as follows(*): from collections import namedtuple Car = namedtuple('Car', 'color mileage') my_car = Car('red', 100) print my_car.color But how can I use a variable to specify the name of the field I want to access? E.g. field = 'color' my_car[field] # doesn't work my_car.field # doesn't work My actual use case is that I'm iterating through a pandas dataframe with for row in data.itertuples() . I am doing an operation on the value from a

Python: Extending a predefined named tuple

时光毁灭记忆、已成空白 提交于 2019-12-18 01:58:55
问题 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

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

旧时模样 提交于 2019-12-17 21:38:27
问题 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? 回答1: 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__

Existence of mutable named tuple in Python?

为君一笑 提交于 2019-12-17 15:08:35
问题 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

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

匆匆过客 提交于 2019-12-17 10:45:08
问题 This question already has answers here : What do *args and **kwargs mean? [duplicate] (5 answers) Closed 5 years ago . 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