Procedures and functions [was Re: Why not allow empty code blocks?]

Steven D'Aprano steve at pearwood.info
Sat Jul 30 23:32:16 EDT 2016


On Sun, 31 Jul 2016 12:17 pm, Chris Angelico wrote:

> Yeah. The distinction means you have a fundamental API difference
> between the procedures (which don't return anything) and the functions
> (whose return values you mightn't care about). 

Correct.

> It means you can't 
> upgrade something from "always returns None" to "returns the number of
> objects frobbed" without breaking compat. 

You shouldn't ever need to. At least that's the theory. In practice its not
quite cut and dried. Procedures are for things which purely operate by
side-effect: they're verbs, doing words:

sleep
print
run
mangle
append
delete

Functions, on the other hand, are transformations. Functions should never
have side-effects, they should take at least one argument and return a new
value.

length of ...
cosine of ...
the date of [this instant]

That's a fairly important conceptual difference, although as I acknowledge
in practice there's more overlap than one might like.



> Conversely, if you decide 
> that any function can be called "as a procedure" (this is what REXX
> does, for instance), then you've just merged the two types of callable
> and distinguished them only in usage.
> 
> Personally, I don't see any value to the distinction at all.

Oh, there's definitely value. I'm just not sure whether the value is worth
the cost of making the distinction.

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.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list