On Sun, Jul 31, 2016, at 00:01, D'Arcy J.M. Cain wrote:
> On Sun, 31 Jul 2016 13:32:16 +1000
> Steven D'Aprano <st...@pearwood.info> wrote:
> > Many beginners make the mistake of writing:
> > 
> > mylist = mylist.sort()
> > 
> > or try to write:
> > 
> > mylist.sort().reverse()
> > 
> > If we had procedures, that would be an obvious error (possibly even a
> > compile-time syntax error) instead of a perplexing source of mystery
> > bugs.
> 
> While neither is a syntax error, the latter is definitely a run-time
> error:

The only way to make it a syntax error would be to have a different
syntax for *calling* procedures. Barring that, all you can do is make
the first one a run-time error.

As Python is a dynamic language, mylist.sort is an object which is
resolved at runtime. When you call this object, its __call__ method is
called and returns the None object. This object is valid for very few
operations (it can be assigned to a variable [or returned], treated as a
boolean, compared for equality, or converted to a string).

In some other languages, procedures have a static return type (often
called "void") which is valid for even fewer operations. You can use it
as a statement expression or within certain contexts (the left side of
C's comma operator, for example) where the value of an expression is
always discarded.

In a hypothetical Python with procedures but no separate syntax for
calling them, you would need to define the __call__ protocol in a way
that it can indicate that the called object is a procedure. Though, it
could probably be handled at the python level by just allowing "return"
or running off the end to do this, requiring "return None" for the
explicit return of a None object.. The real cost is, it would require
that any operation (such as assigning as a variable, checking it as a
boolean, etc) other than discarding it (including returning it, so you'd
need extra bytecode to check rather than merely leaving tail returns on
the stack) check immediately raise an error. This would add extra
processing to nearly all call sites.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to