[Python-ideas] pep-0484 - Forward references and Didactics - be orthogonal
Steven D'Aprano
steve at pearwood.info
Thu Aug 27 04:43:51 CEST 2015
On Tue, Aug 25, 2015 at 07:48:39PM +0200, Sven R. Kunze wrote:
> I think the main issue here is the gab between intuition and what the
> compiler actually does. The following line:
>
> class MyClass: # first appearance of MyClass
>
> basically creates MyClass in the mind of the developer reading this
> piece of code. Thus, he expects to be able to use it after this line.
Intuition according to whom? Some people expect that. Others do not.
People hold all sorts of miscomprehensions and misunderstandings about
the languages they use, and Python is no different.
> However, Python first assigns the class to the name MyClass at the end
> of the class definition. Thus, it is usable only after that.
>
> People get around this (especially since one doesn't need it thus
> often), but it still feels... different.
To me, it feels intuitive and natural. Of course you can't use the class
until after you have finished creating it. To me, alternatives like
Javascript's function hoisting feel weird. This looks like time travel:
// print is provided by the Rhino JS interpreter
var x = f();
print(x);
// multiple pages later
function f() {return "Hello World!";};
How can you call a function that doesn't exist yet? There are even
stranger examples, but for the sake of brevity let's just say that what
seems "intuitive" to one person may be "weird" to another.
With one or two minor exceptions, the Python interactive interpreter
behaves identically to the non-interactive interpreter. If you have
valid Python code, you can run it interactively. The same can't be said
for Javascript. You can't run the above example interactively without
*actual* time travel, if you try, it fails:
[steve at ando ~]$ rhino
Rhino 1.7 release 0.7.r2.3.el5_6 2011 05 04
js> var x = f();
js: "<stdin>", line 2: uncaught JavaScript runtime exception:
ReferenceError: "f" is not defined.
at <stdin>:2
A nice, clean, easy to understand execution model is easy to reason
about. Predictability is much more important than convenience: I much
prefer code which does what I expect over code that saves me a few
characters, or lines, of typing, but surprises me by acting in a way I
didn't expect. The fewer special cases I have to learn, the more
predictable the language and the less often I am surprised.
Python treats functions and classes as ordinary values bound to ordinary
names in the ordinary way: the binding doesn't occur until the statement
is executed. I like it that way.
--
Steve
More information about the Python-ideas
mailing list