[TSBOAPOOOWTDI]using names from modules

Paul Moore p.f.moore at gmail.com
Sun Nov 5 08:35:49 EST 2017


On 5 November 2017 at 01:19, Steve D'Aprano <steve+python at pearwood.info> wrote:
> On Sun, 5 Nov 2017 06:42 am, Stefan Ram wrote:
>
>> What is the one way to do it?
>
> There is no philosophy of "one way to do it" in Python, that is a
> misunderstanding (possibly deliberate...) spread about by Perl users, to
> contrast Python from Perl's "more than one way to do it".
>
> The Zen of Python says:
>
>     There should be one-- and preferably only one --obvious way to do it.
>
>
> The emphasis is on "obvious", not "one". There should be *at least* one, but
> preferably only one, OBVIOUS way to solve any problem.
>
> As for the question of importing names, the obvious way is to use a regular
> import:
>
>
> import math
> y = math.cos(x)
>
>
> which has the advantage of making it obvious where the name comes from, but
> the disadvantage that it is more to type and involves an extra name lookup at
> runtime, which is not free.
>
> But:
>
> - when performance matters
>
> - or the name is very well known
>
> - or you're only using a single name from the module (or at most a few)
>
> - especially if it repeats the module name (e.g. fractions.Fraction)
>
> it is acceptable to use the "from module import name" version:
>
> from math import cos
> y = cos(x)
>
>
> Which you use depends on the situation and personal taste.

Also, if what you are trying to "do" is different (for example, you're
trying to write code that looks familiar to mathematicians) the
obvious way may be different too (so "from math import cos" may be the
obvious approach in that situation).

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.
Paul



More information about the Python-list mailing list