How to make the "not miss" test

I have an API in Python that can return an object, or Noneif the object is not found. I want to avoid exceptions / crashes at runtime, etc., so I want to force users of my API to run a test is not None.

For instance:

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 this?

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

In Python, however, I cannot overload the statement is. Are there any other ways I can implement this function in Python?

+4
source share
3 answers

if x is not None, id(). is , .

if x != None if not x == None, __eq__ __ne__ .

. @Kevin, is , None.

, API, , None. , getattr is not None.

+3

, is.

, , getName(). , , False. ( , , , None __eq__). __nonzero__() False.

:

class GetObjectFailed(object):
    def __nonzero__():
         return False
    def getName():
         return "An error has occurred" # You could specify a specific error message here...

x = getObject(...)
print x # prints "An error has occurred"
if x:
    # This is the recommended way of doing things
    # Do something with the object
    x.proccess()
if x is not None:
    # This will never work
    x.proccess()
if x != None:
    # This is possible but not recommended
    x.proccess()
0

and:

print y and y.getName()

y.getName(), y True y ( None).

, python and, . , (true), . , , .

if:

print 'true' if condition else 'false'
-3

All Articles