"from module import data; print(data)" vs "import module; print(module.data)"

Cameron Simpson cs at zip.com.au
Wed Feb 24 20:22:36 EST 2016


On 24Feb2016 17:07, Dan Stromberg <drsalists at gmail.com> wrote:
>Could people please compare and contrast the two ways of doing imports
>in the Subject line?
>
>I've long favored the latter, but I'm working in a code base that
>prefers the former.

I largely use the former "from module import name, name..." over "import 
module". It makes your code more readable by making your calls to 
module-supplied names less verbose.

That readbility does rely on the names being not too many or not to vague. As a 
glaring counter example to my preference, consider:

  from os.path import join

"join" is a pretty generic name, so my code almost always goes either:

  import os.path

and uses "os.path.join(a, b)" or (recently, in code doing a lot of path 
manipulation):

  from os.path import join as joinpath

as with (real example):

  from os.path import abspath, normpath, join as joinpath

and then using "joinpath(a, b)".

>Is it fair to say that the former increases the surface area of your
>shared (sometimes mutable) state?

It can go the other way. Consider:

  import module
  module.data = 1

versus:

  from module import data
  data = 1

The former directly affects the name "data" in "module"; other users of 
"module" will see this change. The latter binds the _local_ name "data" to 1, 
leaving "module.data" as it was.

Of course both of these are things that are almost never done (look up the term 
"monkey patch" for more info, but the difference is salient.

>It's clear that the former saves keystrokes.
>I find the latter a little more clear, because you don't have to go
>look for where a symbol came from.

I take the view that your should broadly know where a name came from, at least 
as far as what it does, and I will take shorter readably code over 
long.module.names.with.dots. And as mentioned above, is a name is vague (or 
conflicting), there is always the useful:

  from module import name as better_name

>PS: Haskell seems better at the former than Python; Haskell tells you
>if you import two identical symbols from two different places, when
>you try to use one of them - not at import time.  I believe in Python,
>whichever symbol you import last, wins.

It wins in exactly the same way that:

  x = 1
  x = 2

wins for 2: they both run, and after they've run "x" will be bound to 2. Python 
is dynamic, and this is legal. It may be that linting tools like pylint will 
warn about conflicting names from imports.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Python-list mailing list