Skip to content

Commit 40b37a9

Browse files
author
Sylvain MARIE
committed
New method in_stdlib to efficiently check if a module name is part of std lib.
It relies on functools' `@lru_cache` to cache the stdlib list and query results for similar calls. Therefore it is much more efficient than `module_name in stdlib_list()` especially if you wish to perform multiple checks.
1 parent 75a73d8 commit 40b37a9

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

stdlib_list/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@
33
del get_versions
44

55
# Import all the things that used to be in here for backwards-compatibility reasons
6-
from .base import stdlib_list, get_canonical_version, short_versions, long_versions, base_dir, list_dir
6+
from .base import stdlib_list, in_stdlib, get_canonical_version, short_versions, long_versions, base_dir, list_dir

stdlib_list/base.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
import os
44
import sys
55

6+
try:
7+
from functools import lru_cache
8+
except ImportError:
9+
from functools32 import lru_cache
10+
611
base_dir = os.path.dirname(os.path.realpath(__file__))
712

813
list_dir = os.path.join(base_dir, "lists")
@@ -45,3 +50,36 @@ def stdlib_list(version=None):
4550
result = [y for y in [x.strip() for x in f.readlines()] if y]
4651

4752
return result
53+
54+
55+
@lru_cache(maxsize=16)
56+
def _stdlib_list_with_cache(version=None):
57+
"""Internal cached version of `stdlib_list`"""
58+
return stdlib_list(version=version)
59+
60+
61+
@lru_cache(maxsize=256)
62+
def in_stdlib(module_name, version=None):
63+
"""
64+
Return a ``bool`` indicating if module ``module_name`` is in the list of stdlib
65+
symbols for python version ``version``. If ``version`` is ``None`` (default), the
66+
version of current python interpreter is used.
67+
68+
Note that ``True`` will be returned for built-in modules too, since this project
69+
considers they are part of stdlib. See :issue:21.
70+
71+
It relies on ``@lru_cache`` to cache the stdlib list and query results for similar
72+
calls. Therefore it is much more efficient than ``module_name in stdlib_list()``
73+
especially if you wish to perform multiple checks.
74+
75+
:param str|None module_name: The module name (as a string) to query for.
76+
:param str|None version: The version (as a string) whose list of libraries you want
77+
(one of ``"2.6"``, ``"2.7"``, ``"3.2"``, ``"3.3"``, ``"3.4"``, or ``"3.5"``).
78+
If not specified, the current version of Python will be used.
79+
80+
:return: A bool indicating if the given module name is part of standard libraries
81+
for the specified version of Python.
82+
:rtype: list
83+
"""
84+
ref_list = _stdlib_list_with_cache(version=version)
85+
return module_name in ref_list

0 commit comments

Comments
 (0)