Op 14/11/2022 om 4:23 schreef DFS:
On 11/13/2022 9:11 PM, Chris Angelico wrote:
On Mon, 14 Nov 2022 at 11:53, DFS <nos...@dfs.com> wrote:

On 11/13/2022 5:20 PM, Jon Ribbens wrote:
On 2022-11-13, DFS <nos...@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

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:


If it wastes time like that it's invalid.

It's not invalid. In the REPL for example, it does something useful:

>>> x = [1, 2, 3]
>>> x.clear
<built-in method clear of list object at 0x000002947DBBF680>

Others have shown instances where writing a method or function without calling it are useful in a script too.

There are languages that handle this differently. Ruby, for example, calls the function/method even when you don't write the parens, if I'm not mistaken. Personally I don't like that; I much prefer Python's explicitness in making the difference between the value of a function and calling that function. Still, there's something to be said for warnings. I agree with others that such warnings are more the job for a linter than for the language.

FWIW I've been bitten by this in C++ once. I wanted to write something like

if (some_condition())
    foo();

But I forgot the parens after some_condition, so C++ evaluated the function pointer (which was non-NULL so evaluated is true in a boolean context) instead of the return value, and therefore foo() got called unconditionally.

--

"Don't Panic."
        -- Douglas Adams, The Hitchhiker's Guide to the Galaxy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to