Ruby OpenStruct-like Objects in Python with namedtuple
In object-oriented programming, classes are how we define objects and specify their data attributes. Sometimes, we want to create objects with attributes “on the fly”, without having go through the boilerplate of defining a new class. For example, creating mock objects in tests.
Let’s say we want to create a city object with the following properties:
- name
- population
- region
And we want to do this quickly, without having to define a new class.
Ruby
In Ruby, an OpenStruct
can be used for this purpose.
Python
It’s not quite as succinct, but namedtuple
in Python can be used to achieve a similar effect.
In the end, we have an object, city
, with attributes defined on the fly: name
, population
, and region
. All without having to create a new class!
Note: this is not meant to be a replacement for classes, simply another option for creating objects with attributes.