What’s the easiest way to create a naked object that I can assign attributes to?
The specific use case is: I’m doing various operations on a Django object instance, but sometimes the instance is None (there is on instance). In this case I’d like to create the simplest possible fake object such that I can assign values to its attributes (eg. myobject.foo = 'bar').
Basically I’m looking for the Python equivalent of this piece of Javascript:
myobject = {}
myobject.foo = 'bar'
I know I can use a mock object/library for this, but I’m hoping for a very simple solution (as simple as the Javascript above). Is there a way to create a naked object instance? Something like:
myobject = object()
myobject.foo = 'bar'
You need to create a simple class first:
You can make it a one-liner like this:
The call to
typefunctions identically to the previousclassstatement.If you want to be really minimal…
The key is that the built-in types (such as
listandobject) don’t support user-defined attributes, so you need to create a type using either aclassstatement or a call to the 3-parameter version oftype.