Search code examples
pythonpython-importpython-module

Is there any meaningful difference between "import module; import module as blah" and "import module; blah=module"?


This question is merely for my understanding of Python modules.

I am curious if there is any meaningful difference, other than readability, between these two lines:

import module ; import module as blah

and

import module ; blah = module

?


Solution

  • They are identical and result in identical module objects:

    import pathlib as p1
    
    import pathlib
    p2 = pathlib
    
    assert p1 is p2
    assert p1 == p2
    for attr in dir(p1):
        assert getattr(p1, attr) == getattr(p2, attr)
    for attr in dir(p2):
        assert getattr(p1, attr) == getattr(p2, attr)
    

    The above works in CPython 3.11 and PyPy 3.10 (v7.3.12).

    In CPython specifically, the version with as uses fewer bytecode operations:

    Python 3.11.6 (main, Oct  2 2023, 17:46:45) [Clang 13.1.6 (clang-1316.0.21.2.5)]
    Type 'copyright', 'credits' or 'license' for more information
    IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: def g():
       ...:     import pathlib as p2
       ...:     return p2
       ...:
    
    In [2]: def f():
       ...:     import pathlib
       ...:     p1 = pathlib
       ...:     return p1
       ...:
    
    In [3]: dis(g)
      1           0 RESUME                   0
    
      2           2 LOAD_CONST               1 (0)
                  4 LOAD_CONST               0 (None)
                  6 IMPORT_NAME              0 (pathlib)
                  8 STORE_FAST               0 (p2)
    
      3          10 LOAD_FAST                0 (p2)
                 12 RETURN_VALUE
    
    In [4]: dis(f)
      1           0 RESUME                   0
    
      2           2 LOAD_CONST               1 (0)
                  4 LOAD_CONST               0 (None)
                  6 IMPORT_NAME              0 (pathlib)
                  8 STORE_FAST               0 (pathlib)
    
      3          10 LOAD_FAST                0 (pathlib)
                 12 STORE_FAST               1 (p1)
    
      4          14 LOAD_FAST                1 (p1)
                 16 RETURN_VALUE
    

    But this difference should not be noticeable in any real-world usage.

    Note that you do not need to write import module before import module as foo. In every form of import, the module is loaded in its entirety and stored in memory under its original name.