简体   繁体   中英

what is better approach to do?

I have piece of cake that is returning None in case exception is caught.

   def getObject(ver):
        av = None
        try:
            av = getTestObject(ver)
        except exceptions.ObjectNotFound, err:
            _log.info("%r not Found", obj.fromTestObject(ver))
        return av

or this is better ?

def getObject(ver):
    try:
        av = getTestObject(ver)
    except exceptions.ObjectNotFound, err:
        _log.info("%r not Found", obj.fromTestObject(ver))
    else:
         return av

A shorter (more Pythonic, IMHO) equivalent to your first code snippet is as follows:

def getObject(ver):
    try:
        return getTestObject(ver)
    except exceptions.ObjectNotFound, err:
        _log.info("%r not Found", obj.fromTestObject(ver))

This works because python functions implicitly return None if control reaches the end of the function without encountering a return (as would be the case if your exception is caught).

First code is better.

Reasons:

Exception may occur before the return value is set to variable av.

In first code, None will be returned if exception occured. In second code, return value is undefined if exception occured.

None is better than undefined as return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM