Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set an optional variable in named tuple

Tags:

python

from collections import namedtuple

FooT = namedtuple('Foo', 'foo bar')
def Foo(foo=None, bar=None):
  return FooT(foo,bar)

foo = Foo()
foo.foo = 29
throws attribute error

So, my use case is a datastructure which have optional fields.. but should be able to modify it if desired..

like image 228
frazman Avatar asked Jul 17 '15 21:07

frazman


2 Answers

A defaultdict should be appropriate for what you want. It works by providing it a function on construction which it calls every time an unset element is accessed. Here's a demo:

>>> from collections import defaultdict
>>> d = defaultdict(lambda:None)
>>> d['foo'] = 10
>>> d['bar'] = 5
>>> print d['baz']
None
>>> d['baz'] = 15
>>> print d['baz']
15
like image 142
Brien Avatar answered Sep 24 '22 15:09

Brien


Tuples are, by definition, immutable. Namedtuples follow this pattern as well.

In python3 it appears there is a SimpleNamespace [1] that you can use. If you want to simply use a read/write datastructure though you could create a class and put constraints on its members.

[1] - Why Python does not support record type i.e. mutable namedtuple

like image 20
Ned Rockson Avatar answered Sep 22 '22 15:09

Ned Rockson