Fix Python – Creating an empty object in Python


Asked By – Smiles

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.

Now we will see solution for issue: Creating an empty object in Python


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'

This question is answered By – aychedee

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0