Ruby-like struct in Python #2


Ruby provides a very handy type called OpenStruct to create objects. It brings the opportunity to add fields to objects during the runtime. Here is its Python counterpart.

In the previous post I showed Struct from esu which helps creating new types with fields and methods. That has a sibling, called OpenStruct which helps creating objects on the fly.

Usage

Ruby’s OpenStruct (doc:2.6.5) inspired it, and it looks as follows.

We have two ways to declare fields. One way is to pass a dict to the ctor, where keys are the fields, while values are values assigned to the given field.

We can introduce fields as referencing them by using dot-notation.

from esu import OpenStruct

bob = OpenStruct()
bob.name = Bob
bob.age = 54
print(bob) # => [name=Bob, age=54]

su = OpenStruct({'name': 'Su', 'gender': 'female'})
su.employed = True
print(su) # => [name=Su, gender=female, employed=True]

Implementation

How can we reference fields without they would be declared previously?

Python provides __getattr__(self, name) and __setattr__(self, name, value) methods which are called when a field or a method is referenced or called. Getter is called when field or method is read while setter is called when those two are written.

In this post we saw another struct type from esu, called OpenStruct. Enjoy using it!

You can find the repository fo the package here: https://github.com/torokmark/esu
The pip package can be found here: https://pypi.org/project/esu
The documentation is here: https://esu.readthedocs.io