Creating an empty object in Python

Are there any shortcuts for defining an empty object in Python or do you always have to create an instance of a custom empty class?

Edit: I mean an empty object usable for duck typing.

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__

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'


Back to homepage or read more recommendations: