The Python Oracle

Python : is it ok returning both boolean and string?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 Python : Is It Ok Returning Both Boolean And String?
01:22 Answer 1 Score 28
01:31 Answer 2 Score 6
02:12 Answer 3 Score 4
02:34 Answer 4 Score 12
03:00 Thank you

--

Full question
https://stackoverflow.com/questions/6578...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 28


Would it not be more suitable to return a None instead of False?




ANSWER 2

Score 12


I believe the orthodox Python design would be to return None. The manual says:

None

This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false.




ANSWER 3

Score 6


The convenient thing is to return an empty string in this case.

Besides an empty string in Python will evaluate to False anyway. So you could call it like:

if Myfunc(s, timeout):
    print "success"

Addition: As pointed out by S.Lott the true Pythonic way is to return None. Though I choose to return strings in string related funcs. A matter of preference indeed.

Also I assume the caller of Myfunc only cares about getting a string to manipulate on - empty or not. If the caller needs to check about timeout issues, etc.. it's better to use exceptions or returning None.




ANSWER 4

Score 4


Maybe if you return a tuple like (False, None) and (True, test) it would be better, as you can evaluate them separatedly and not add unnecesary complexity.

EDIT: Perhaps the string that appeared on the serial port is "" (maybe expected), so returning True can say that it arrived that way.