Python Glossary Русский

all Python 3inspectfunction

inspect.getmodulename()

members and modules

Given a file path, returns the module name without its extension, or None if the extension is not a module one. It imports nothing.

Syntax

inspect.getmodulename(path) -> str | None

This is pure string work: the file need not exist. Extensions are checked against importlib.machinery.all_suffixes(), so .py, .pyc and the platform's C extension suffix (.so or .pyd) give a name while .txt gives None. It does not find package names: a directory path gives None, and a path to pkg/__init__.py gives literally '__init__'. Enclosing package names (pkg.mod) are not added.

Examples

import inspect
print(inspect.getmodulename('app/utils.py'))  # → utils
print(inspect.getmodulename('cache/utils.pyc'))  # → utils
print(inspect.getmodulename('notes.txt'))  # → None
print(inspect.getmodulename('app/__init__.py'))  # → __init__
print(inspect.getmodulename('app'))  # → None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy