Using "importlib.metadata"
**************************

버전 3.8에 추가.

**Source code:** Lib/importlib/metadata.py

참고:

  이 기능은 잠정적이며 표준 라이브러리의 일반적인 버전 의미와 다를 수
  있습니다.

"importlib.metadata" is a library that provides for access to
installed package metadata.  Built in part on Python's import system,
this library intends to replace similar functionality in the entry
point API and metadata API of "pkg_resources".  Along with
"importlib.resources" in Python 3.7 and newer (backported as
importlib_resources for older versions of Python), this can eliminate
the need to use the older and less efficient "pkg_resources" package.

By "installed package" we generally mean a third-party package
installed into Python's "site-packages" directory via tools such as
pip.  Specifically, it means a package with either a discoverable
"dist-info" or "egg-info" directory, and metadata defined by **PEP
566** or its older specifications. By default, package metadata can
live on the file system or in zip archives on "sys.path".  Through an
extension mechanism, the metadata can live almost anywhere.


개요
====

"pip"를 사용하여 설치한 패키지의 버전 문자열을 얻고 싶다고 가정해 봅시
다. 우선 가상 환경을 만들고 그 안에 뭔가 설치합니다:

   $ python3 -m venv example
   $ source example/bin/activate
   (example) $ pip install wheel

다음을 실행하여 "wheel"에 대한 버전 문자열을 얻을 수 있습니다:

   (example) $ python
   >>> from importlib.metadata import version  
   >>> version('wheel')  
   '0.32.3'

"console_scripts", "distutils.commands"와 다른 것들과 같은 그룹 키로
진입 지점 집합을 얻을 수도 있습니다. 각 그룹은 EntryPoint 객체의 시퀀
스를 포함합니다.

여러분은 배포 메타데이터를 얻을 수 있습니다:

   >>> list(metadata('wheel'))  
   ['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Requires-Dist', 'Requires-Dist']

또한 배포의 버전 번호를 가져오고, 구성 파일을 나열하고, 배포의 배포 요
구 사항 리스트를 얻을 수 있습니다.


기능적 API
==========

이 패키지는 공용 API를 통해 다음과 같은 기능을 제공합니다.


진입 지점
---------

"entry_points()" 함수는 그룹 키를 갖는 모든 진입 지점의 딕셔너리를 반
환합니다. 진입 지점은 "EntryPoint" 인스턴스로 나타냅니다; 각
"EntryPoint"에는 ".name", ".group" 및 ".value" 어트리뷰트가 있고 값을
결정하는 ".load()" 메서드가 있습니다.

>>> eps = entry_points()  
>>> list(eps)  
['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
>>> scripts = eps['console_scripts']  
>>> wheel = [ep for ep in scripts if ep.name == 'wheel'][0]  
>>> wheel  
EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
>>> main = wheel.load()  
>>> main  
<function main at 0x103528488>

"group"과 "name"은 패키지 저자가 정의한 임의의 값이며 일반적으로 클라
이언트는 특정 그룹에 대한 모든 진입 지점을 찾으려고 합니다. 진입 지점
의 정의와 사용법에 대한 자세한 정보는 the setuptools docs를 읽으십시오
.


배포 메타데이터
---------------

모든 배포는 "metadata()" 함수를 사용하여 추출할 수 있는 몇 가지 메타
데이터가 포함되어 있습니다:

   >>> wheel_metadata = metadata('wheel')  

반환된 데이터 구조의 [1] 키는 메타데이터 키워드의 이름을 지정하고, 해
당 값은 배포 메타데이터에서 구문 분석하지 않은 채로 반환됩니다:

   >>> wheel_metadata['Requires-Python']  
   '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'


배포 버전
---------

"version()" 함수는 배포의 버전 번호를 문자열로 가져오는 가장 빠른 방법
입니다:

   >>> version('wheel')  
   '0.32.3'


배포 파일
---------

You can also get the full set of files contained within a
distribution.  The "files()" function takes a distribution package
name and returns all of the files installed by this distribution.
Each file object returned is a "PackagePath", a "pathlib.Path" derived
object with additional "dist", "size", and "hash" properties as
indicated by the metadata.  For example:

   >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0]  
   >>> util  
   PackagePath('wheel/util.py')
   >>> util.size  
   859
   >>> util.dist  
   <importlib.metadata._hooks.PathDistribution object at 0x101e0cef0>
   >>> util.hash  
   <FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>

일단 파일을 얻으면, 내용을 읽을 수도 있습니다:

   >>> print(util.read_text())  
   import base64
   import sys
   ...
   def as_bytes(s):
       if isinstance(s, text_type):
           return s.encode('utf-8')
       return s

메타 데이터 파일 목록 파일(RECORD나 SOURCES.txt)이 누락된 경우,
"files()"는 "None"을 반환합니다. 대상 배포에 메타 데이터가 있음이 알려
지지 않았을 때, 이 조건에 대한 보호로 호출자는 "files()"에 대한 호출을
always_iterable이나 다른 것으로 감쌀 수 있습니다.


배포 요구 사항
--------------

배포의 전체 요구 사항을 얻으려면, "requires()" 함수를 사용하십시오:

   >>> requires('wheel')  
   ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]


배포
====

위의 API가 가장 일반적이며 편리한 사용법이지만, "Distribution" 클래스
에서 모든 정보를 얻을 수 있습니다. "Distribution"은 파이썬 패키지의 메
타 데이터를 나타내는 추상 객체입니다. "Distribution" 인스턴스를 얻을
수 있습니다:

   >>> from importlib.metadata import distribution  
   >>> dist = distribution('wheel')  

따라서, 버전 번호를 얻는 다른 방법은 "Distribution" 인스턴스를 사용하
는 것입니다:

   >>> dist.version  
   '0.32.3'

"Distribution" 인스턴스에서 사용할 수 있는 모든 종류의 추가 메타 데이
터가 있습니다:

   >>> dist.metadata['Requires-Python']  
   '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
   >>> dist.metadata['License']  
   'MIT'

The full set of available metadata is not described here.  See **PEP
566** for additional details.


검색 알고리즘 확장하기
======================

Because package metadata is not available through "sys.path" searches,
or package loaders directly, the metadata for a package is found
through import system finders.  To find a distribution package's
metadata, "importlib.metadata" queries the list of *meta path finders*
on "sys.meta_path".

파이썬의 기본 "PathFinder"에는 일반적인 파일 시스템 기반 경로에서 로드
된 배포를 찾기 위해 "importlib.metadata.MetadataPathFinder"를 호출하는
훅이 포함되어 있습니다.

The abstract class "importlib.abc.MetaPathFinder" defines the
interface expected of finders by Python's import system.
"importlib.metadata" extends this protocol by looking for an optional
"find_distributions" callable on the finders from "sys.meta_path" and
presents this extended interface as the "DistributionFinder" abstract
base class, which defines this abstract method:

   @abc.abstractmethod
   def find_distributions(context=DistributionFinder.Context()):
       """Return an iterable of all Distribution instances capable of
       loading the metadata for packages for the indicated ``context``.
       """

"DistributionFinder.Context" 객체는 검색할 경로와 일치할 이름을 가리키
는 ".path"와 ".name" 프로퍼티를 제공하고 다른 관련 문맥을 제공할 수 있
습니다.

이것이 실제로 의미하는 것은, 파일 시스템이 아닌 위치에서 배포 패키지
메타 데이터를 찾는 것을 지원하려면, "Distribution"을 서브 클래싱하고
추상 메서드를 구현해야 한다는 것입니다. 그런 다음 사용자 정의 파인더의
"find_distributions()" 메서드에서, 이 파생된 "Distribution"의 인스턴스
를 반환하십시오.

-[ 각주 ]-

[1] Technically, the returned distribution metadata object is an
    "email.message.EmailMessage" instance, but this is an
    implementation detail, and not part of the stable API.  You should
    only use dictionary-like methods and syntax to access the metadata
    contents.
