Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer

What do you mean by "empty object"? Instance of class object? You can simply run

a = object()

or maybe you mean initialization to the null reference? Then you can use

a = None
share|improve this answer
1  
I wonder what the OP will be able to do with a defined either as object() or None because in such cases, a has no namespace __dict__ and no attribute can be added to a like that for example a.x = 10. –  eyquem Jan 5 '14 at 23:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.