Last Updated: December 26, 2018
·
361
· deontologician

Simple Python object that allows attribute additions

Lots of times when testing an interface in the command line, it's really convenient to be able to create a simple object that holds a few attributes. It'd be nice if you could do something like this:

obj = object()
obj.foo = 3

but alas, you cannot (object doesn't like getting unexpected attributes added to it).

Mock is a wonderful library for doing actual unit testing etc. But if you find yourself "just needing an object now", this can come in handy:

obj = type('blank_object', (object,), {})()
obj.foo = 3
function_requiring_an_object_with_foo_attribute(obj)

The magic line above essentially creates a new class with the name 'blank_object', inheriting from object, and with no class methods. Then it immediately creates an instance of that class.

What's that you say? Yes, the type function is pretty awesome.