[Tutor] Do _all_ Python builtin methods/functions return "None" IF ...
Steven D'Aprano
steve at pearwood.info
Fri Jan 26 23:32:33 EST 2018
On Fri, Jan 26, 2018 at 08:56:31PM -0600, boB Stepp wrote:
> ... they are not designed to explicitly return something else?
Yes. In the absence of an explicit return, all Python functions will
return None.
> The reason I ask is that I almost fell into the following trap:
>
> <GCE trap>
> py3: a_lst = [0, 1, 2]
> py3: b_lst = a_lst.append(3)
> py3: a_lst, b_lst
> ([0, 1, 2, 3], None)
>
> Instead of "None" I was expecting "[0, 1, 2, 3]". Obviously I have a
> GCE (Gross Conceptual Error).
> </GCE trap>
>
> I almost sent the above as my question, but then I realized (Finally!)
> that lst.append() performs an append operation on lst and returns
> None. Just like print() returns None.
>
> So my actual question is: For these types of methods/functions, is
> Python Both versions 2 and 3) consistent throughout and *always*
> returns None?
Mostly. Python's policy is that functions and methods which operate by
side-effect, or modify the object in place (such as list.append, insert,
sort, reverse, etc, or dict.update, clear etc), return None. That is to
prevent the sort of error where you do this:
alist = [4, 1, 2, 5, 3]
blist = alist.sort()
assert blist == [1, 2, 3, 4, 5]
assert alist == [4, 1, 2, 5, 3] # this will fail
thinking that list.sort returns a copy.
So in general, such functions all return None. However, there have been
a few changes, such as file.write method, which used to return None in
Python 2 but in Python 3 returns the number of characters actually
written.
--
Steve
More information about the Tutor
mailing list