Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return an empty dict instead of None?

Tags:

python

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.

like image 823
Frankie Ribery Avatar asked May 13 '11 03:05

Frankie Ribery


People also ask

Is an empty dict none?

If the dictionary is empty, it returns None which is not == False .

What does empty dict return?

In the example above, we used the bool() function to see if a Python dictionary is empty. In short, a dictionary passed into the bool() function will return False if a dictionary is empty.

Does an empty dictionary return false?

If the dictionary is empty, the “if condition” returns true; otherwise, it returns false.

Should I use dict () or {}?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


1 Answers

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.

like image 97
sateesh Avatar answered Sep 20 '22 07:09

sateesh