Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise flexible struct definition

Tags:

python

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?

like image 511
rwallace Avatar asked Feb 17 '14 14:02

rwallace


2 Answers

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)
like image 157
6502 Avatar answered Nov 18 '22 22:11

6502


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')
like image 6
roippi Avatar answered Nov 18 '22 22:11

roippi