Alex Rivera | Logout

Python simple naked objects

Asked 2012-05-30T20:17:09.527
49

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'
Edit
Report

1 Answer

53

You need to create a simple class first:

class Foo(object):
    pass

myobject = Foo()
myobject.foo = 'bar'

You can make it a one-liner like this:

myobject = type("Foo", (object,), {})()
myobject.foo = 'bar'

The call to type functions identically to the previous class statement.

If you want to be really minimal...

myobject = type("", (), {})()

The key is that the built-in types (such as list and object) don't support user-defined attributes, so you need to create a type using either a class statement or a call to the 3-parameter version of type.

answered 2012-05-30T20:20:38.777

Your Answer