[TSBOAPOOOWTDI]using names from modules

Steve D'Aprano steve+python at pearwood.info
Sun Nov 5 09:13:54 EST 2017


On Mon, 6 Nov 2017 12:54 am, Stefan Ram wrote:

> Paul Moore <p.f.moore at gmail.com> writes:
>>But regardless, the Zen isn't intended to be taken quite as literally
>>as the OP was trying to do. It's a statement of principles, not a set
>>of rules.
> 
>   What I am looking for is a default notation to use in my
>   beginner's tutorial and also to recommand for beginners.

When I first started learning Python, I had a bit of difficulty with the two
import forms. For about an hour, until I experimented in the interactive
interpreter until I got it.

Part of the problem at the time was that I had no concept of "namespaces" or
modules.

If your students are experienced in other languages, don't treat them like
dummies. They'll probably understand about namespaces and variable scopes.
Teach them that math.cos is the syntax for accessing a name "cos" inside
the "math" namespace, and they'll get it. Teach them that the from...import
version brings the name into the current scope, and they'll get that too. You
might have to give them analogous examples from whatever languages they're
used to.

If your students are completely new to this, like I was, then it might help to
start them with just the "import math" form, and then later introduce 
"from...import" as syntactic sugar for:

import math
cos = math.cos
del math

Although I wouldn't literally teach `del` at this point, I'd just leave it out
and and "except that the name 'math' isn't actually made available".


>   Learners have a limited capacity for learning and storing
>   information.

People don't learn isolated facts too well. But they learn *models* which they
can then infer behaviour from VERY well. This is why the Principle of Least
Surprise is so important for usable interfaces and APIs.

If you try to teach things as isolated facts, students will struggle. But:

- teach import math first;

- then show how `from math import cos` is syntactic sugar for making a local
alias for math.cos;

- then you can show that there's no particular reason why the names have to be
the same:

from math import cos as mycos

is just sugar for

import math
mycos = math.cos


But don't teach them this:

> |from math import *

There's no reason for beginners to use wildcard imports until they've mastered
*not* using wildcard imports.



-- 
Steve
“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