Creating an empty object in Python

You said it in the question, but as no answer mentioned it with code, this is probably one of the cleanest solutions:

class Myobject:
    pass

x = Myobject()
x.test = "Hello, world!"  # working


You can use type to create a new class on the fly and then instantiate it. Like so:

>>> t = type('test', (object,), {})()
>>> t
<__main__.test at 0xb615930c>

The arguments to type are: Class name, a tuple of base classes, and the object's dictionary. Which can contain functions (the object's methods) or attributes.

You can actually shorten the first line to

>>> t = type('test', (), {})()
>>> t.__class__.__bases__
(object,)

Because by default type creates new style classes that inherit from object.

type is used in Python for metaprogramming.

But if you just want to create an instance of object. Then, just create an instance of it. Like lejlot suggests.

Creating an instance of a new class like this has an important difference that may be useful.

>>> a = object()
>>> a.whoops = 1
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'whoops'

Where as:

>>> b = type('', (), {})()
>>> b.this_works = 'cool'
>>> 

Yes, in Python 3.3 SimpleNamespace was added

Unlike object, with SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.

Example:

import types

x = types.SimpleNamespace()
x.happy = True

print(x.happy) # True

del x.happy
print(x.happy) # AttributeError. object has no attribute 'happy'

One simple, less-terrifying-looking way to create an empty(-ish) object is to exploit the fact that functions are objects in Python, including Lambda Functions:

obj = lambda: None
obj.test = "Hello, world!"

For example:

In [18]: x = lambda: None

In [19]: x.test = "Hello, world!"

In [20]: x.test
Out[20]: 'Hello, world!'

Tags:

Python

Oop