Upgrade to Pro — share decks privately, control downloads, hide ads and more …

WIP: What happens behind execution of an `import` statement?

Shivashis Padhi
May 02, 2020
150

WIP: What happens behind execution of an `import` statement?

Shivashis Padhi

May 02, 2020
Tweet

Transcript

  1. What happens when you do >> from spam import ham

    - Shivashis Padhi
  2. Packages in Python

  3. None
  4. But how can we import a package from a different

    directory?
  5. $PATH, and $PYTHONPATH

  6. None
  7. Regular and Namespace packages

  8. The import system

  9. sys.modules

  10. Finders and loaders

  11. Finders - examples • locate built-in modules • locate frozen

    modules • import path - imagine $PATH and $PYTHONPATH
  12. Finders - function • If a finder is capable of

    handling import, it returns a module spec. • module spec contains module’s metadata i.e path, name, etc. The import machinery uses this spec to load modules later
  13. find_spec

  14. importing spam.ham

  15. Import hooks and PEP 302

  16. sys.path_hooks sys.meta_path

  17. Loaders After spec object is returned from a finder, loaders

    are used to execute the module and store its reference in sys.modules
  18. None
  19. None
  20. None
  21. Code demonstration of an import hooks’ implementation.

  22. importing submodules

  23. What else can you do with import hooks? • full

    control after what happens after ‘import x’ • importing from ftp, https, authorization checks. • importing from a variety of storage, not just .py/.pyc
  24. Thank you