Finding Modules & Packages Using Import

markkimjr·2021년 1월 18일
0
post-thumbnail

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:
['',
 '/Users/song-eun-u/anaconda3/bin',
 '/Users/song-eun-u/anaconda3/lib/python36.zip',
 '/Users/song-eun-u/anaconda3/lib/python3.6',
 '/Users/song-eun-u/anaconda3/lib/python3.6/lib-dynload',
 '/Users/song-eun-u/anaconda3/lib/python3.6/site-packages',
 '/Users/song-eun-u/anaconda3/lib/python3.6/site-packages/aeosa',
 '/Users/song-eun-u/anaconda3/lib/python3.6/site-packages/IPython/extensions',
 '/Users/song-eun-u/.ipython']

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 (main.py) must always use absolute imports, since relative imports are based on the name of the current main module

The init.py file is used to initialize a package. If a package contains init.py, 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
profile
#mambamentality 🐍

0개의 댓글