Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the object() built-in useful?

I'm trying to figure out what I would use the object() built-in function for. It takes no arguments, and returns a "featureless object" of the type that is common to all Python classes, and has all the methods that are common to all Python classes.

To quote Jack Skellington, WHAT. IS. THIS?

like image 809
temporary_user_name Avatar asked Sep 22 '13 01:09

temporary_user_name


1 Answers

Even if you do not need to program with it, object serves a purpose: it is the common class from which all other objects are derived. It is the last class listed by the mro (method resolution order) method. We need a name and object for this concept, and object serves this purpose.

Another use for object is to create sentinels.

sentinel = object()

This is often used in multithreaded programming -- passed through queues -- to signal a termination event. We might not want to send None or any other value since the queue handler may need to interpret those values as arguments to be processed. We need some unique value that no other part of the program may generate.

Creating a sentinel this way provides just such a unique object that is sure not to be a normal queue value, and thus can be tested for and used as a signal for some special event. There are other possibilities, such as creating a class, or class instance, or a function, but all those alternatives are bigger, more resource heavy, and not as pithy as object().

like image 186
unutbu Avatar answered Oct 10 '22 17:10

unutbu