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..
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With