Skip to content
Advertisement

Should I return an empty dict instead of None?

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

JavaScript

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

JavaScript

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.

JavaScript

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:

JavaScript

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