Building on @Edmund's answer, this solution pulls the list from the official website:
def standard_libs(version=None, top_level_only=True):
import re
from urllib.request import urlopen
if version is None:
import sys
version = sys.version_info
version = f"{version.major}.{version.minor}"
url = f"https://docs.python.org/{version}/py-modindex.html"
with urlopen(url) as f:
page = f.read()
modules = set()
for module in re.findall(r'#module-(.*?)[\'"]',
page.decode('ascii', 'replace')):
if top_level_only:
module = module.split(".")[0]
modules.add(module)
return modules
It returns a set. For example, here are the modules that were added between 3.5 and 3.10:
>>> standard_libs("3.10") - standard_libs("3.5")
{'contextvars', 'dataclasses', 'graphlib', 'secrets', 'zoneinfo'}
Since this is based on the official documentation, it doesn't include undocumented modules, such as:
- Easter eggs, namely
this
and antigravity
- Internal modules, such as
genericpath
, posixpath
or ntpath
, which are not supposed to be used directly (you should use os.path
instead). Other internal modules: idlelib
(which implements the IDLE editor), opcode
, sre_constants
, sre_compile
, sre_parse
, pyexpat
, pydoc_data
, nt
.
- All modules with a name starting with an underscore (which are also internal), except for
__main__', '_thread', and '__future__
which are public and documented.
If you're concerned that the website may be down, you can just cache the list locally. For example, you can use the following function to create a small Python module containing all the module names:
def create_stdlib_module_names(
module_name="stdlib_module_names",
variable="stdlibs",
version=None,
top_level_only=True):
stdlibs = standard_libs(
version=version, top_level_only=top_level_only)
with open(f"{module_name}.py", "w") as f:
f.write(f"{variable} = {stdlibs!r}\n")
Here's how to use it:
>>> create_stdlib_module_names() # run this just once
>>> from stdlib_module_names import stdlibs
>>> len(stdlibs)
207
>>> "collections" in stdlibs
True
>>> "numpy" in stdlibs
False
sysconfig.get_python_lib(standard_lib=True)
also gives me the path of my virtualenv which doesn't have all the standard library modules. – Thermostat