Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force "is not None" test

Tags:

python

I have an API in Python which can return an object, or None if no object is found. I want to avoid run-time exceptions/crashes, etc., hence I want to force the users of my API, to do an is not None test.

For example:

x = getObject(...)
if x is not None:
   print x.getName()  #should be o.k.


y = getObject(...)
print y.getName() # print an error to the log

How can I achieve that?

In comparable code in C++, I can add a flag that will be checked when I call the getName(); the flag is set only upon comparing the object to NULL.

In Python, however, I am unable to overload the is operator. Are there any other ways I can achieve that functionality in Python?

like image 215
Max Shifrin Avatar asked Apr 08 '15 12:04

Max Shifrin


1 Answers

You cannot force the use of if x is not None because you cannot override the behavior of id(). The is operator internally compares the ids of the two objects being compared, and you have no way of controlling that behavior.

However, you can force the use of if x != None or if not x == Noneby overriding the __eq__ and __ne__ methods of your class, respectively.

This is not good practice, however. As @Kevin has noted in the comments, is is the preferred operator to use when comparing to None.

What I would do is write clear and organized documentation for this API, and then clearly warn users that the instantiation could fail and return None. Then, gently nudge users towards good practices by providing an example with the built-in getattr function or an example with the is not None check.

like image 92
Shashank Avatar answered Oct 11 '22 02:10

Shashank