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

Chris Angelico rosuav at gmail.com
Thu Feb 25 23:11:51 EST 2016


On Fri, Feb 26, 2016 at 2:56 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Thu, Feb 25, 2016 at 5:40 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> If you take "Special cases are not special enough" seriously, you will not
>> use `import os.path` since os is not a package:
>>
>> py> os.__package__
>> ''
>>
>> and os.path is not part of os, it's just a publicly exposed attribute which
>> merely happens to be a module. Being a module doesn't make it special, it's
>> just another name in the os namespace. I trust that you wouldn't insist on
>> writing:
>>
>> import os.listdir
>>
>> (especially since that doesn't work). Neither should you insist on writing
>> `import os.path`, since path is documented as a public part of the os
>> module. It has done so since at least Python 1.5.
>
> I disagree. The fact that os is not a package is an implementation
> detail. I for one wasn't even aware of it prior to reading your post.
>
> The name of the concurrent.futures module is "concurrent.futures". If
> you want to use it, you import concurrent.futures, not concurrent.
>
> Likewise, the name of the os.path module is "os.path". If you want to
> use it, you import os.path, not os.
>
> The fact that concurrent and os are two different types of things is irrelevant.
>
> Besides, packages *are* modules. To take another example, collections
> is a package (I checked), and collections.abc is a module. But
> collections also contains things that aren't modules. If you want to
> use collections.abc, you have to import it, but at the same time you
> don't import collections.Counter. This demonstrates that the analog
> you suggest between os.path and os.listdir is flawed.

Steven is right, though. You can "from module import X" and it doesn't
matter whether 'module' is a package or a non-package module; but if
you say "import module.X", aside from special cases like os.path,
you're asserting that 'module' is a package and 'X' is a module within
that package. Yes, a package is a module, but the dotted lookup
requires a package.

ChrisA


More information about the Python-list mailing list