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?
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 == None
by 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With