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

Cameron Simpson cs at cskk.id.au
Mon Nov 14 17:11:10 EST 2022


On 13Nov2022 22:23, DFS <nospam at dfs.com> wrote:
>On 11/13/2022 9:11 PM, Chris Angelico wrote:
>> [ ... `x.clear` ... ]
>>No part of it is invalid, so nothing causes a problem. For instance,
>>you can write this:
>
>If it wastes time like that it's invalid.

It's a valid expression.

It looks to your eye like a no-op, but at actually Python _looks up the 
name `clear`_ on an object (which happens to be a `list`). That is a 
real thing to do, and can have side effects.

While most of the examples here have been in the REPL where running an 
expression with no side effects is itself useful, because the REPL can 
print the result, I've personally got some real world code with a bare 
`some_object.attribute` line. I'm not sure where, or I'd show it, but I 
_think_ it was probably prepriming a cached object property. There might 
have been a more expressive way to do that, but it was a bare attribute 
lookup with side effects, _used for those side effects_.

>This is an easy check for the interpreter to make.

It really isn't, given that (a) this isn't known by the interpreter to 
be a `list` until runtime and (b) that would need embedding special 
knowledge that looking up an attribute on a `list` has no side effects 
(versus some other things, where it is not the case).

Linters are the best place for this: they warn about probably-mistakes 
idioms like this, and can have slightly deep knowledge of the code's 
semantics sometimes.

>If I submit a suggestion to python-list at python.org will it just show 
>up here?  Or do the actual Python devs intercept it?

Nah, it'll go through.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list