Finding Modules & Packages Using Import

markkimjr·2021년 1월 18일

Import Search Order

  1. sys.modules
    sys.modules is a dictionary of modules and packages that have already been imported.
  2. built-in modules
    Built-in python modules from the python library
  3. sys.path
    sys.path is a list of strings (directories) that python searches through to find a package. Example below:

1. sys.modules 와 sys.path의 차이점을 서술해 주세요
sys.modules is a dictionary of modules and packages that have already been imported, whereas sys.path is a list of strings of directory names. After searching through sys.modules and its built-in modules, python searches sys.path for any modules packages that have been imported by the user.

2. sys 도 import 해야하는 모듈입니다. 파이썬은 sys 모듈의 위치를 어떻게 찾을 수 있을까요?
sys is already a built-in module, so python looks for sys in its built-in modules.

3. Absolute path와 relative path의 차이점을 서술해 주세요.
Absolute path - search path that allows you to import a module/package from anywhere within your project file (takes your main project file as the starting point)
Relative path - takes the local directory from which you are importing as the starting point and finds other directories relative to it

ImportError: attempted relative import with no known parent package

*** Key point: The module of a python package ( must always use absolute imports, since relative imports are based on the name of the current main module

The file is used to initialize a package. If a package contains, the code in the file runs automatically.

  • used to shorten path length when importing
  • used to limit which functions/classes/variables can be imported from the package
  • can selectively run code whenever the package it is contained within is imported
#mambamentality 🐍

0개의 댓글