namedtuple

Malformed String error - Python - converting string repr. of dictionary

大憨熊 提交于 2019-12-08 04:23:44
问题 When I do ast.literal_eval() , I get ValueError: malformed string for the line below z = ast.literal_eval(a) . Why is this not working? (Pls. note - "something" in the line below has 4 or more namedtuples) for thing in something: a = thing._asdict() z = ast.literal_eval(a) print z If I do a simple print a , I get OrderedDict([('a', 0.0), ('b', 0.0), ('c', 0.0), ('d', 100.0)]) Without ast.literal_eval(a) , when I try to use "a" as a dictionary, it raises AttributeError: 'str' object has no

Is `namedtuple` really as efficient in memory usage as tuples? My test says NO

你说的曾经没有我的故事 提交于 2019-12-06 18:08:03
问题 It is stated in the Python documentation that one of the advantages of namedtuple is that it is as memory-efficient as tuples. To validate this, I used iPython with ipython_memory_usage. The test is shown in the images below: The test shows that: 10000000 instances of namedtuple used about 850 MiB of RAM 10000000 tuple instances used around 73 MiB of RAM 10000000 dict instances used around 570 MiB of RAM So namedtuple used much more memory than tuple ! Even more than dict !! What do you think

Serializing namedtuples via PyYAML

心不动则不痛 提交于 2019-12-06 09:43:42
I'm looking for some reasonable way to serialize namedtuples in YAML using PyYAML. A few things I don't want to do: Rely on a dynamic call to add a constructor/representor/resolver upon instantiation of the namedtuple. These YAML files may be stored and re-loaded later, so I cannot rely on the same runtime environment existing when they are restored. Register the namedtuples in global. Rely on the namedtuples having unique names I was thinking of something along these lines: class namedtuple(object): def __new__(cls, *args, **kwargs): x = collections.namedtuple(*args, **kwargs) class New(x):

Harmful side effects for different namedtuples with same typename?

陌路散爱 提交于 2019-12-05 22:40:20
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 whether or not this has any particular pitfalls since the typename argument to namedtuple is always the same,

Structure accessible by attribute name or index options

你说的曾经没有我的故事 提交于 2019-12-05 04:52:35
I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd. In trying to figure it out, I've only come across C implementations of the above types. Nothing specifically in Python. What is the Python native way to create this kind of object? I apologize if this has been widely covered already. In searching for an answer, I must be missing some fundamental concept that is excluding me from finding an answer. You

What is a nicer alternative to a namedtuples _replace?

[亡魂溺海] 提交于 2019-12-05 04:11:42
Take this code: >>> import urlparse >>> parts = urlparse.urlparse('http://docs.python.org/library/') >>> parts = parts._replace(path='/3.0'+parts.path) parts._replace works but as it is an underscored method, it's supposed to be internal, and not used. Is there an alternative? I don't want to do: >>> parts = parts[:2] + ('/3.0'+parts.path,) + parts[3:] Because that makes it an ordinary tuple, and not a namedtuple, and doing: >>> parts = namedtuple(scheme=parts.scheme, netloc=parts.netloc, etc etc) is kinda stupid. :) Ideas? The reason methods of namedtuple start with an initial underscore is

Is `namedtuple` really as efficient in memory usage as tuples? My test says NO

拥有回忆 提交于 2019-12-05 01:03:16
It is stated in the Python documentation that one of the advantages of namedtuple is that it is as memory-efficient as tuples. To validate this, I used iPython with ipython_memory_usage . The test is shown in the images below: The test shows that: 10000000 instances of namedtuple used about 850 MiB of RAM 10000000 tuple instances used around 73 MiB of RAM 10000000 dict instances used around 570 MiB of RAM So namedtuple used much more memory than tuple ! Even more than dict !! What do you think? Where did I go wrong? Billy A simpler metric is to check the size of equivalent tuple and namedtuple

Pretty print namedtuple

穿精又带淫゛_ 提交于 2019-12-04 22:25:29
I tried pprint from pprint , but its output is just one line, there is no multiline output and no indentation. I use the builtin function vars to get the namedtuple as a dictionary. However, it returns an OrderedDict which pprint won't indent, so I convert it to a dict : >>> from collections import namedtuple >>> Busbar = namedtuple('Busbar', 'id name voltage') >>> busbar = Busbar(id=102, name='FACTORY', voltage=21.8) With pprint and dict : >>> from pprint import pprint >>> pprint(dict(vars(busbar))) {'id': 102, 'name': 'FACTORY', 'voltage': 21.8} The pprint PrettyPrinter in Python 3 is much

Did something about `namedtuple` change in 3.5.1?

守給你的承諾、 提交于 2019-12-04 16:10:54
问题 On Python 3.5.0: >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >>> c = cluster(a=4, b=9) >>> c Cluster(a=4, b=9) >>> vars(c) OrderedDict([('a', 4), ('b', 9)]) On Python 3.5.1: >>> from collections import namedtuple >>> cluster = namedtuple('Cluster', ['a', 'b']) >>> c = cluster(a=4, b=9) >>> c Cluster(a=4, b=9) >>> vars(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: vars() argument must have __dict__ attribute

How to cast tuple into namedtuple?

孤人 提交于 2019-12-04 15:15:25
问题 I'd like to use namedtuples internally, but I want to preserve compatibility with users that feed me a ordinary tuple. from collections import namedtuple tuplePi=(1,3.14,"pi") #Normal tuple Record=namedtuple("MyNamedTuple", ["ID", "Value", "Name"]) namedE=Record(2, 2.79, "e") #Named tuple namedPi=Record(tuplePi) #Error TypeError: __new__() missing 2 required positional arguments: 'Value' and 'Name' tuplePi.__class__=Record TypeError: __class__ assignment: only for heap types 回答1: You can use