Procedures and functions [was Re: Why not allow empty code blocks?]

Chris Angelico rosuav at gmail.com
Sun Jul 31 02:55:09 EDT 2016


On Sun, Jul 31, 2016 at 4:40 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> While neither is a syntax error, the latter is definitely a run-time
>> error:
>>
>>>>> mylist.sort().reverse()
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> AttributeError: 'NoneType' object has no attribute 'reverse'
>
> Hence my description of it as a perplexing source of mystery bugs. How did
> mylist suddenly turn into None?
>
> Well, it didn't, but it sure looks like it did, for those who didn't realise
> that sort() is intended to be used *as if* it were a procedure with no
> return value. If it *actually* had no return value, Python could give a
> more useful error message:
>
> ProcedureError: list.sort() has no return value

Fortunately, a linter can pick this up (maybe even right in your
editor, before you move off the line of code). Particularly if type
hints are available, a linter can say "Hey, this function always
returns None, and you're assigning it to something - that looks
wrong".

ChrisA



More information about the Python-list mailing list