|
3 | 3 | import os
|
4 | 4 | import sys
|
5 | 5 |
|
| 6 | +try: |
| 7 | + from functools import lru_cache |
| 8 | +except ImportError: |
| 9 | + from functools32 import lru_cache |
| 10 | + |
6 | 11 | base_dir = os.path.dirname(os.path.realpath(__file__))
|
7 | 12 |
|
8 | 13 | list_dir = os.path.join(base_dir, "lists")
|
@@ -45,3 +50,36 @@ def stdlib_list(version=None):
|
45 | 50 | result = [y for y in [x.strip() for x in f.readlines()] if y]
|
46 | 51 |
|
47 | 52 | 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