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.

require 'ostruct'

city = OpenStruct.new(
  name: 'Rivendell',
  population: 100,
  region: 'Eriador'
)

city.name # Rivendell
city.population # 100
city.region # Eriador

Python

It’s not quite as succinct, but namedtuple in Python can be used to achieve a similar effect.

from collections import namedtuple

City = namedtuple('City', [
  'name',
  'population',
  'region'
])

city = City('Rivendell', 100, 'Eriador')

city.name # Rivendell
city.population # 100
city.region # Eriador

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.