I need to define a bunch of flexible structs (objects with a simple collection of named fields, where you can add new fields later, but I don't need methods or inheritance or anything like that) in Python 2.7. (The context is that I'm reading stuff from binary files with struct.unpack_from, then adding further data to the results.)
A class meets the requirements, e.g.
class Thing:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
The only downside being that each field name must be written out three times. collections.namedtuple gives a more precise definition syntax but you can't add fields to the resulting objects.
Is there a way to get flexibility of a class with at least some of the brevity of collections.namedtuple?
A pattern that I found sometimes useful is
class Obj(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
and you can use it like
p = Obj(x=10, y=20)
Hidden away in the argparse
module is Namespace
:
from argparse import Namespace
n = Namespace(foo='Foo', bar='Bar')
n
Out[3]: Namespace(bar='Bar', foo='Foo')
n.bar
Out[4]: 'Bar'
n.hey = 'Hey'
n
Out[6]: Namespace(bar='Bar', foo='Foo', hey='Hey')
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