This repository has been archived on 2025-11-17. You can view files and clone it, but cannot push or open issues or pull requests.
Files
pypages/modules/module_list.py
2025-11-16 18:01:30 +01:00

153 lines
5.7 KiB
Python

"""
Module for listing available Python modules and objects.
"""
import pydoc
import inspect
import sys
from typing import List, Dict, Any
class ModuleList:
"""
Provides lists of available Python modules and objects for documentation.
"""
@staticmethod
def get_standard_modules() -> List[Dict[str, Any]]:
"""
Get list of standard library modules.
Returns:
List of dictionaries with module information
"""
modules = []
stdlib_paths = [p for p in sys.path if 'site-packages' not in p]
# Common standard library modules
common_modules = [
'os', 'sys', 'json', 'datetime', 'collections', 'itertools',
'functools', 'operator', 'string', 're', 'math', 'random',
'statistics', 'decimal', 'fractions', 'array', 'bisect',
'heapq', 'copy', 'pickle', 'sqlite3', 'hashlib', 'hmac',
'secrets', 'uuid', 'pathlib', 'shutil', 'glob', 'fnmatch',
'linecache', 'tempfile', 'fileinput', 'csv', 'configparser',
'netrc', 'xdrlib', 'plistlib', 'codecs', 'unicodedata',
'stringprep', 'readline', 'rlcompleter', 'struct', 'codecs',
'types', 'copyreg', 'pprint', 'reprlib', 'enum', 'numbers',
'collections.abc', 'io', 'argparse', 'getopt', 'logging',
'getpass', 'curses', 'platform', 'errno', 'ctypes', 'threading',
'multiprocessing', 'concurrent', 'subprocess', 'sched', 'queue',
'select', 'selectors', 'asyncio', 'socket', 'ssl', 'email',
'html', 'http', 'urllib', 'xml', 'webbrowser', 'cgi', 'cgitb',
'wsgiref', 'urllib', 'xmlrpc', 'ipaddress', 'audioop', 'aifc',
'sunau', 'wave', 'chunk', 'colorsys', 'imghdr', 'sndhdr',
'ossaudiodev', 'gettext', 'locale', 'calendar', 'cmd', 'shlex',
'tkinter', 'turtle', 'pydoc', 'doctest', 'unittest', 'test',
'lib2to3', 'typing', 'dataclasses', 'contextlib', 'abc',
'atexit', 'traceback', 'future', 'gc', 'inspect', 'site',
'fpectl', 'distutils', 'ensurepip', 'venv', 'zipapp', 'faulthandler',
'pdb', 'profile', 'pstats', 'timeit', 'trace', 'tracemalloc',
'warnings', 'contextvars', 'dataclasses', 'weakref', 'types',
'copy', 'pprint', 'reprlib', 'enum', 'numbers', 'collections.abc'
]
for mod_name in common_modules:
try:
if mod_name in sys.modules:
mod = sys.modules[mod_name]
else:
mod = __import__(mod_name)
if inspect.ismodule(mod):
modules.append({
'name': mod_name,
'type': 'module',
'doc': inspect.getdoc(mod) or ''
})
except (ImportError, AttributeError):
continue
return sorted(modules, key=lambda x: x['name'])
@staticmethod
def get_builtin_objects() -> List[Dict[str, Any]]:
"""
Get list of builtin objects (types, functions, etc.).
Returns:
List of dictionaries with builtin object information
"""
objects = []
builtins_module = __import__('builtins')
for name in dir(builtins_module):
if not name.startswith('_'):
try:
obj = getattr(builtins_module, name)
obj_type = 'function' if inspect.isbuiltin(obj) or inspect.isfunction(obj) else 'type'
objects.append({
'name': name,
'type': obj_type,
'full_name': f'builtins.{name}',
'doc': ''
})
except Exception:
continue
return sorted(objects, key=lambda x: x['name'])
@staticmethod
def get_module_contents(module_name: str) -> List[Dict[str, Any]]:
"""
Get list of objects in a module.
Args:
module_name: Name of the module
Returns:
List of dictionaries with object information
"""
objects = []
try:
if module_name in sys.modules:
mod = sys.modules[module_name]
else:
mod = __import__(module_name)
if not inspect.ismodule(mod):
return objects
for name in dir(mod):
if name.startswith('_'):
continue
try:
obj = getattr(mod, name)
obj_type = 'unknown'
if inspect.ismodule(obj):
obj_type = 'module'
elif inspect.isclass(obj):
obj_type = 'class'
elif inspect.isfunction(obj) or inspect.ismethod(obj):
obj_type = 'function'
elif inspect.isbuiltin(obj):
obj_type = 'function'
else:
obj_type = 'object'
full_name = f"{module_name}.{name}"
objects.append({
'name': name,
'type': obj_type,
'full_name': full_name,
'doc': ''
})
except Exception:
continue
except Exception as e:
print(f"Error getting module contents for {module_name}: {e}")
return sorted(objects, key=lambda x: x['name'])