[Tutor] returning None from function definition
Cameron Simpson
cs at cskk.id.au
Sat Oct 24 07:38:04 EDT 2020
On 24Oct2020 11:54, Manprit Singh <manpritsinghece at gmail.com> wrote:
>What about returning None instead of False inside Function
>definition in this case ?
Kipping over the prime functions, I just want to recommend against
returning None instead of False. Your function returns a true/false
result, so it _should_ return a Boolean, which in Python is one of the
two special values True and False.
It _happens_ that your programme runs using None for false, just as it
would run using 0 for false, because Python falls back to a "nonzero"
style test in conditions if it is not handed a Boolean (type bool). But
it is very bad practice.
Secondly, think about linting your programmes. Supposing you put some
type annotations on your code, like this:
def prime(n:int) -> bool:
... test n for primality ...
If you run a linter over this code which understands type annotations,
it will rightly complain about returning None, because you've asserted
that this is a function returning a bool, which is the _natrual_ type
for logic results.
Finally, all python functions return values. When you just do a plain:
return
or fall off the end of a function with no explicit return statement,
that returns None.
Just don't do this.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list