In code, list.clear doesn't throw error - it's just ignored

Chris Angelico rosuav at gmail.com
Sun Nov 13 21:11:11 EST 2022


On Mon, 14 Nov 2022 at 11:53, DFS <nospam at dfs.com> wrote:
>
> On 11/13/2022 5:20 PM, Jon Ribbens wrote:
> > On 2022-11-13, DFS <nospam at dfs.com> wrote:
> >> In code, list.clear is just ignored.
> >> At the terminal, list.clear shows
> >> <built-in method clear of list object at 0x000001C9CFEC4240>
> >>
> >>
> >> in code:
> >> x = [1,2,3]
> >> x.clear
> >> print(len(x))
> >> 3
> >>
> >> at terminal:
> >> x = [1,2,3]
> >> x.clear
> >> <built-in method clear of list object at 0x000001C9CFEC4240>
> >> print(len(x))
> >> 3
> >>
> >>
> >> Caused me an hour of frustration before I noticed list.clear() was what
> >> I needed.
> >>
> >> x = [1,2,3]
> >> x.clear()
> >> print(len(x))
> >> 0
> >
> > If you want to catch this sort of mistake automatically then you need
> > a linter such as pylint:
> >
> >    $ cat test.py
> >    """Create an array and print its length"""
> >
> >    array = [1, 2, 3]
> >    array.clear
> >    print(len(array))
> >    $ pylint -s n test.py
> >    ************* Module test
> >    test.py:4:0: W0104: Statement seems to have no effect (pointless-statement)
>
>
> Thanks, I should use linters more often.
>
> But why is it allowed in the first place?
>
> I stared at list.clear and surrounding code a dozen times and said
> "Looks right!  Why isn't it clearing the list?!?!"
>
> 2 parens later and I'm golden!
>

No part of it is invalid, so nothing causes a problem. For instance,
you can write this:

>>> 1

And you can write this:

>>> 1 + 2

And you can write this:

>>> print(1 + 2)

But only one of those is useful in a script. Should the other two be
errors? No. But linters WILL usually catch them, so if you have a good
linter (especially built into your editor), you can notice these
things.

ChrisA


More information about the Python-list mailing list