Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import a.b also imports a?

When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?

e.g. this works

python -c "import os.path; print os.getcwd()"

Shouldn't I explicitly import os for os.getcwd to be available ?

like image 310
analogue Avatar asked Feb 18 '14 21:02

analogue


People also ask

Should I use import or from import?

When Use 'import' and When 'from import' Use from import when you want to save yourself from typing the module name over and over again. In other words, when referring to a member of the module many times in the code. Use import when you want to use multiple members of the module.

What is import * in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


2 Answers

There's an important thing to know about packages, that is that there is a difference between being loaded and being available.

With import a you load module a (which can be a package) and make it available under the name a.

With from a import b you load module a (which definitely is a package), then load module a.b and make only this available under the name b. Notice that a also got loaded in the process, so any initialization this is supposed to do will have happened.

With import a.b you load both and make both available (under the names a and a.b).

like image 90
Alfe Avatar answered Nov 15 '22 20:11

Alfe


This is a good question. If you look at the source code for os.py you find this line:

sys.modules['os.path'] = path

So there's our module. But what's path? Well that depends on your OS. For Windows, it's defined in this block:

elif 'nt' in _names:
    name = 'nt'
    linesep = '\r\n'
    from nt import *
    try:
        from nt import _exit
    except ImportError:
        pass
    import ntpath as path

    import nt
    __all__.extend(_get_exports_list(nt))
    del nt

Basically, os.path is special in this context.

Short version: Python does some stuff behind the scenes to make os.path. You probably shouldn't rely on it to get other modules. "Explicit is better than implicit" is how the zen goes.

like image 21
austin Avatar answered Nov 15 '22 21:11

austin