I've been trying to sort an array of number using the sort function but I forgot to write parentheses.
arr.sort
instead of
arr.sort()
My question is why can't python detect this error and inform me like Java can? The program kept compiling fine but because I was inputting the numbers in ascending order, the problem wouldn't show up.
arr.sort
is syntactically valid. It's just not the syntax you wanted. Syntactically, arr.sort
is an attribute access expression for the sort
attribute of whatever arr
evaluates to; semantically, when arr
is a list, arr.sort
evaluates to a method object for arr
's sort
method, so it's perfectly fine at runtime too.
It's kind of like method references in Java, but since Python is dynamically typed and has method objects, it doesn't need to go through all the functional interface and poly expression stuff Java 8 had to add to support list::sort
syntax.
Syntax errors are only for outright invalid syntax.