3

I saw the following in a student's script, and to my surprise it works:

>>> import os.path

The question, in brief, is: How is this different from simple import os? Or is it the same, except for necessitating that os.path exists?

As you can see below, it doesn't define path in my scope but os.

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']

So the question is: What does python do with this? For sure, it imports (and hence executes) the module os. It also ensures that os.path does resolve to something valid. (Thanks to @Lee and @Stuart for the links to the documentation that confirms it.) But is there more? Or is import pkg.submod always equivalent to import pkg (provided pkg.submod exists)?

If I import os, it already imports/executes any modules that os itself imports; so os.path is already loaded. Are there arrangements (not too exotic) where importing pkg.submod could lead to different code being executed, or in different order, or otherwise having different side effects, than just importing pkg? And are there legitimate use cases for the multi-segment form? (To put it differently: What's the point?)

alexis
  • 48,685
  • 16
  • 101
  • 161

1 Answers1

3

From the docs:

[The fully qualified name of the module] will be used in various phases of the import search, and it may be the dotted path to a submodule, e.g. foo.bar.baz. In this case, Python first tries to import foo, then foo.bar, and finally foo.bar.baz. If any of the intermediate imports fail, an ImportError is raised.

So, to answer your original question, it seems that if os is a valid package, then the whole module is imported. So, as you suggest, the sub-module form would be used to validate that os.path exists within the os module, rather than just importing the module os.path.

If you want to only import the path module, then you can use the from ... import ... syntax:

>>> from os import path
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'path']

See also: from … import vs import .

Community
  • 1
  • 1
Lee Netherton
  • 21,347
  • 12
  • 68
  • 102
  • The whole module is imported for sure, sorry I didn't make it clear that I knew that. The question is what other effects there are. Are there differences? If I just import `os`, doesn't it already import everything `os` imports, hence also `path`? – alexis May 24 '16 at 13:16
  • Yes, I guess that `import os.path` can be used to validate that `path` exists within the `os` module, otherwise it would raise an `ImportError`. – Lee Netherton May 24 '16 at 13:20