Skip to content
Advertisement

Should I return an empty dict instead of None?

I have a method that currently returns None or a dict.

result,error = o.apply('grammar')

The caller currently has to check for the existence of two keys to decide what kind of object was returned.

if 'imperial' in result:
    # yay
elif 'west' in result:
    # yahoo
else:
    # something wrong?

Because result can be None, I’m thinking of returning an empty dict instead, so the caller does not need to check for that. What do you think ?

For comparison, in the re module, the result of calling match can result in None.

p = re.compile('w+')
m = p.match( 'whatever' )

But in this case, m is an object instance. In my case, I am returning a dict which should either be empty or have some entries.

Advertisement

Answer

Yes I think returning an empty dict (or where applicable an empty list) is preferable to returning None as this avoids an additional check in the client code.

EDIT: Adding some code sample to elaborate:

def result_none(choice):
    mydict = {}
    if choice == 'a':
        mydict['x']  = 100
        mydict['y']  = 1000
        return mydict
    else:
        return None

def result_dict(choice):
    mydict = {}
    if choice == 'a':
        mydict['x']  = 100
        mydict['y']  = 1000
    return mydict

test_dict = result_dict('b')
if test_dict.get('x'):
    print 'Got x'
else:
    print 'No x'

test_none = result_none('b')
if test_none.get('x'):
    print 'Got x'
else:
    print 'No x'

In the above code the check test_none.get(x) throws an AttributeError as result_none method can possibly return a None. To avoid that I have to add an additional check and might rewrite that line as: if test_none is not None and test_none.get('x') which is not at all needed if the method were returning an empty dict. As the example shows the check test_dict.get('x') works fine as the method result_dict returns an empty dict.

Advertisement