What behavior would you expect?

Chris Angelico rosuav at gmail.com
Thu Feb 19 15:11:13 EST 2015


On Fri, Feb 20, 2015 at 7:03 AM, Denis McMahon <denismfmcmahon at gmail.com> wrote:
> On the one hand, the return type of a function (when it returns, rather
> than raising an exception) should be consistent to itself, even if using
> a language where types are not declared.
>

Yes, so I'd advise against having a function sometimes return a string
and sometimes a dict. Sure. But None gets a bit of a special pass
here; in a lot of languages, what you'd have is a "nullable" type (eg
in C you might declare the return value as "pointer to char", and
either return a pointer to a string, or NULL), but in Python, you
return None for the special case. So in a sense, "str or None" is not
so inconsistent.

> I guess at the end of the day the programmer has to consider and
> determine which is most appropriate to his application, given the case.

Indeed. But knowing that your caller quite possibly won't check, what
would you do, to increase the chances of the unexpected being noticed?
Again, it comes down to expectations. If 25% of queries are going to
return "nothing found", then having that be the empty string is fine -
you can be pretty sure your users will test for it. But if that's an
extremely rare case, then it may be worth raising an exception
instead, so it's safe even if someone forgets to test for the unusual.

ChrisA



More information about the Python-list mailing list