winipedia-utils 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- winipedia_utils/__init__.py +1 -0
- winipedia_utils/concurrent/__init__.py +1 -0
- winipedia_utils/concurrent/concurrent.py +242 -0
- winipedia_utils/concurrent/multiprocessing.py +115 -0
- winipedia_utils/concurrent/multithreading.py +93 -0
- winipedia_utils/consts.py +22 -0
- winipedia_utils/data/__init__.py +1 -0
- winipedia_utils/data/dataframe.py +7 -0
- winipedia_utils/django/__init__.py +27 -0
- winipedia_utils/django/bulk.py +536 -0
- winipedia_utils/django/command.py +334 -0
- winipedia_utils/django/database.py +304 -0
- winipedia_utils/git/__init__.py +1 -0
- winipedia_utils/git/gitignore.py +80 -0
- winipedia_utils/git/pre_commit/__init__.py +1 -0
- winipedia_utils/git/pre_commit/config.py +60 -0
- winipedia_utils/git/pre_commit/hooks.py +109 -0
- winipedia_utils/git/pre_commit/run_hooks.py +49 -0
- winipedia_utils/iterating/__init__.py +1 -0
- winipedia_utils/iterating/iterate.py +29 -0
- winipedia_utils/logging/__init__.py +1 -0
- winipedia_utils/logging/ansi.py +6 -0
- winipedia_utils/logging/config.py +64 -0
- winipedia_utils/logging/logger.py +26 -0
- winipedia_utils/modules/__init__.py +1 -0
- winipedia_utils/modules/class_.py +76 -0
- winipedia_utils/modules/function.py +86 -0
- winipedia_utils/modules/module.py +361 -0
- winipedia_utils/modules/package.py +350 -0
- winipedia_utils/oop/__init__.py +1 -0
- winipedia_utils/oop/mixins/__init__.py +1 -0
- winipedia_utils/oop/mixins/meta.py +315 -0
- winipedia_utils/oop/mixins/mixin.py +28 -0
- winipedia_utils/os/__init__.py +1 -0
- winipedia_utils/os/os.py +61 -0
- winipedia_utils/projects/__init__.py +1 -0
- winipedia_utils/projects/poetry/__init__.py +1 -0
- winipedia_utils/projects/poetry/config.py +91 -0
- winipedia_utils/projects/poetry/poetry.py +30 -0
- winipedia_utils/setup.py +36 -0
- winipedia_utils/testing/__init__.py +1 -0
- winipedia_utils/testing/assertions.py +23 -0
- winipedia_utils/testing/convention.py +177 -0
- winipedia_utils/testing/create_tests.py +286 -0
- winipedia_utils/testing/fixtures.py +28 -0
- winipedia_utils/testing/tests/__init__.py +1 -0
- winipedia_utils/testing/tests/base/__init__.py +1 -0
- winipedia_utils/testing/tests/base/fixtures/__init__.py +1 -0
- winipedia_utils/testing/tests/base/fixtures/fixture.py +6 -0
- winipedia_utils/testing/tests/base/fixtures/scopes/__init__.py +1 -0
- winipedia_utils/testing/tests/base/fixtures/scopes/class_.py +33 -0
- winipedia_utils/testing/tests/base/fixtures/scopes/function.py +7 -0
- winipedia_utils/testing/tests/base/fixtures/scopes/module.py +31 -0
- winipedia_utils/testing/tests/base/fixtures/scopes/package.py +7 -0
- winipedia_utils/testing/tests/base/fixtures/scopes/session.py +224 -0
- winipedia_utils/testing/tests/base/utils/__init__.py +1 -0
- winipedia_utils/testing/tests/base/utils/utils.py +82 -0
- winipedia_utils/testing/tests/conftest.py +26 -0
- winipedia_utils/text/__init__.py +1 -0
- winipedia_utils/text/string.py +126 -0
- winipedia_utils-0.1.0.dist-info/LICENSE +21 -0
- winipedia_utils-0.1.0.dist-info/METADATA +350 -0
- winipedia_utils-0.1.0.dist-info/RECORD +64 -0
- winipedia_utils-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,80 @@
|
|
1
|
+
"""Git utilities for file and directory operations.
|
2
|
+
|
3
|
+
This module provides utility functions for working with Git repositories,
|
4
|
+
including checking if paths are in .gitignore and walking directories
|
5
|
+
while respecting gitignore patterns. These utilities help with file operations
|
6
|
+
that need to respect Git's ignore rules.
|
7
|
+
"""
|
8
|
+
|
9
|
+
import os
|
10
|
+
from collections.abc import Generator
|
11
|
+
from pathlib import Path
|
12
|
+
|
13
|
+
import pathspec
|
14
|
+
|
15
|
+
from winipedia_utils.logging.logger import get_logger
|
16
|
+
|
17
|
+
logger = get_logger(__name__)
|
18
|
+
|
19
|
+
|
20
|
+
def path_is_in_gitignore(relative_path: str | Path) -> bool:
|
21
|
+
"""Check if a path matches any pattern in the .gitignore file.
|
22
|
+
|
23
|
+
Args:
|
24
|
+
relative_path: The path to check, relative to the repository root
|
25
|
+
|
26
|
+
Returns:
|
27
|
+
True if the path matches any pattern in .gitignore, False otherwise
|
28
|
+
|
29
|
+
"""
|
30
|
+
as_path = Path(relative_path)
|
31
|
+
is_dir = (
|
32
|
+
bool(as_path.suffix == "") or as_path.is_dir() or str(as_path).endswith(os.sep)
|
33
|
+
)
|
34
|
+
is_dir = is_dir and not as_path.is_file()
|
35
|
+
|
36
|
+
as_posix = as_path.as_posix()
|
37
|
+
if is_dir and not as_posix.endswith("/"):
|
38
|
+
as_posix += "/"
|
39
|
+
|
40
|
+
gitignore_path = Path(".gitignore")
|
41
|
+
if not gitignore_path.exists():
|
42
|
+
return False # No ignore rules
|
43
|
+
|
44
|
+
spec = pathspec.PathSpec.from_lines(
|
45
|
+
"gitwildmatch", gitignore_path.read_text().splitlines()
|
46
|
+
)
|
47
|
+
|
48
|
+
return spec.match_file(as_posix)
|
49
|
+
|
50
|
+
|
51
|
+
def walk_os_skipping_gitignore_patterns(
|
52
|
+
folder: str | Path = ".",
|
53
|
+
) -> Generator[tuple[Path, list[str], list[str]], None, None]:
|
54
|
+
"""Walk a directory tree while skipping paths that match gitignore patterns.
|
55
|
+
|
56
|
+
Similar to os.walk, but skips directories and files that match patterns
|
57
|
+
in the .gitignore file.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
folder: The root directory to start walking from
|
61
|
+
|
62
|
+
Yields:
|
63
|
+
Tuples of (current_path, directories, files) for each directory visited
|
64
|
+
|
65
|
+
"""
|
66
|
+
folder = Path(folder)
|
67
|
+
for root, dirs, files in os.walk(folder):
|
68
|
+
rel_root = Path(root).relative_to(".")
|
69
|
+
|
70
|
+
# skip all in patterns in .gitignore
|
71
|
+
if path_is_in_gitignore(rel_root):
|
72
|
+
logger.info("Skipping %s because it is in .gitignore", rel_root)
|
73
|
+
dirs.clear()
|
74
|
+
continue
|
75
|
+
|
76
|
+
# remove all files that match patterns in .gitignore
|
77
|
+
valid_files = [f for f in files if not path_is_in_gitignore(rel_root / f)]
|
78
|
+
valid_dirs = [d for d in dirs if not path_is_in_gitignore(rel_root / d)]
|
79
|
+
|
80
|
+
yield rel_root, valid_dirs, valid_files
|
@@ -0,0 +1 @@
|
|
1
|
+
"""__init__ module for winipedia_utils.git.pre_commit."""
|
@@ -0,0 +1,60 @@
|
|
1
|
+
"""Has config utilities for pre-commit."""
|
2
|
+
|
3
|
+
from pathlib import Path
|
4
|
+
from typing import Any
|
5
|
+
|
6
|
+
import yaml
|
7
|
+
|
8
|
+
from winipedia_utils.logging.logger import get_logger
|
9
|
+
|
10
|
+
logger = get_logger(__name__)
|
11
|
+
|
12
|
+
|
13
|
+
def load_pre_commit_config() -> dict[str, Any]:
|
14
|
+
"""Load the pre-commit config."""
|
15
|
+
path = Path(".pre-commit-config.yaml")
|
16
|
+
if not path.exists():
|
17
|
+
path.touch()
|
18
|
+
return yaml.safe_load(path.read_text()) or {}
|
19
|
+
|
20
|
+
|
21
|
+
def dump_pre_commit_config(config: dict[str, Any]) -> None:
|
22
|
+
"""Dump the pre-commit config."""
|
23
|
+
path = Path(".pre-commit-config.yaml")
|
24
|
+
with path.open("w") as f:
|
25
|
+
yaml.safe_dump(config, f, sort_keys=False)
|
26
|
+
|
27
|
+
|
28
|
+
def _get_pre_commit_config_dict() -> dict[str, Any]:
|
29
|
+
"""Get the content for a pre-commit config file as a dictionary."""
|
30
|
+
return {
|
31
|
+
"repo": "local",
|
32
|
+
"hooks": [
|
33
|
+
{
|
34
|
+
"id": "winipedia-utils",
|
35
|
+
"name": "winipedia-utils",
|
36
|
+
"entry": "python -m winipedia_utils.git.pre_commit.run_hooks",
|
37
|
+
"language": "system",
|
38
|
+
"always_run": True,
|
39
|
+
"pass_filenames": False,
|
40
|
+
}
|
41
|
+
],
|
42
|
+
}
|
43
|
+
|
44
|
+
|
45
|
+
def _pre_commit_config_is_correct() -> bool:
|
46
|
+
"""Check if the pre-commit config is correct."""
|
47
|
+
config = load_pre_commit_config()
|
48
|
+
package_hook_config = _get_pre_commit_config_dict()
|
49
|
+
return bool(config.get("repos", [{}])[0] == package_hook_config)
|
50
|
+
|
51
|
+
|
52
|
+
def _add_package_hook_to_pre_commit_config() -> None:
|
53
|
+
"""Add the winipedia-utils hook to the pre-commit config."""
|
54
|
+
config = load_pre_commit_config()
|
55
|
+
package_hook_config = _get_pre_commit_config_dict()
|
56
|
+
# insert at the beginning of the list
|
57
|
+
if not _pre_commit_config_is_correct():
|
58
|
+
logger.info("Adding winipedia-utils hook to pre-commit config")
|
59
|
+
config["repos"] = [package_hook_config, *config.get("repos", [])]
|
60
|
+
dump_pre_commit_config(config)
|
@@ -0,0 +1,109 @@
|
|
1
|
+
"""module contains functions that return the input for subprocess.run().
|
2
|
+
|
3
|
+
Each function is named after the hook it represents. The docstring of each function
|
4
|
+
describes the hook it represents. The function returns a list of strings that
|
5
|
+
represent the command to run. The first string is the command, and the following
|
6
|
+
strings are the arguments to the command. These funcs will be called by
|
7
|
+
run_hooks.py, which will pass the returned list to subprocess.run().
|
8
|
+
"""
|
9
|
+
|
10
|
+
from pathlib import Path
|
11
|
+
|
12
|
+
from winipedia_utils.projects.poetry.poetry import (
|
13
|
+
POETRY_PATH,
|
14
|
+
POETRY_RUN_ARGS,
|
15
|
+
POETRY_RUN_PYTHON_ARGS,
|
16
|
+
POETRY_RUN_RUFF_ARGS,
|
17
|
+
)
|
18
|
+
|
19
|
+
|
20
|
+
def _update_package_manager() -> list[str | Path]:
|
21
|
+
"""Update the package manager.
|
22
|
+
|
23
|
+
This function returns the input for subprocess.run() to update the package
|
24
|
+
manager.
|
25
|
+
"""
|
26
|
+
return [POETRY_PATH, "self", "update"]
|
27
|
+
|
28
|
+
|
29
|
+
def _install_packages() -> list[str | Path]:
|
30
|
+
"""Install all dependencies.
|
31
|
+
|
32
|
+
This function returns the input for subprocess.run() to install all dependencies.
|
33
|
+
"""
|
34
|
+
return [POETRY_PATH, "install"]
|
35
|
+
|
36
|
+
|
37
|
+
def _update_packages() -> list[str | Path]:
|
38
|
+
"""Update all dependencies.
|
39
|
+
|
40
|
+
This function returns the input for subprocess.run() to update all dependencies.
|
41
|
+
"""
|
42
|
+
return [POETRY_PATH, "update"]
|
43
|
+
|
44
|
+
|
45
|
+
def _lock_dependencies() -> list[str | Path]:
|
46
|
+
"""Lock the dependencies.
|
47
|
+
|
48
|
+
This function returns the input for subprocess.run() to lock the dependencies.
|
49
|
+
"""
|
50
|
+
return [POETRY_PATH, "lock"]
|
51
|
+
|
52
|
+
|
53
|
+
def _check_configurations() -> list[str | Path]:
|
54
|
+
"""Check that poetry.lock and pyproject.toml is up to date.
|
55
|
+
|
56
|
+
This function returns the input for subprocess.run() to check that poetry.lock
|
57
|
+
is up to date.
|
58
|
+
"""
|
59
|
+
return [POETRY_PATH, "check", "--strict"]
|
60
|
+
|
61
|
+
|
62
|
+
def _creating_tests() -> list[str | Path]:
|
63
|
+
"""Create all tests for the project.
|
64
|
+
|
65
|
+
This function returns the input for subprocess.run() to create all tests.
|
66
|
+
"""
|
67
|
+
return [*POETRY_RUN_PYTHON_ARGS, "-m", "winipedia_utils.testing.create_tests"]
|
68
|
+
|
69
|
+
|
70
|
+
def _linting() -> list[str | Path]:
|
71
|
+
"""Check the code.
|
72
|
+
|
73
|
+
This function returns the input for subprocess.run() to lint the code.
|
74
|
+
It autofixes all errors that can be autofixed with --fix.
|
75
|
+
"""
|
76
|
+
return [*POETRY_RUN_RUFF_ARGS, "check", "--fix"]
|
77
|
+
|
78
|
+
|
79
|
+
def _formating() -> list[str | Path]:
|
80
|
+
"""Format the code.
|
81
|
+
|
82
|
+
This function calls ruff format to format the code.
|
83
|
+
"""
|
84
|
+
return [*POETRY_RUN_RUFF_ARGS, "format"]
|
85
|
+
|
86
|
+
|
87
|
+
def _type_checking() -> list[str | Path]:
|
88
|
+
"""Check the types.
|
89
|
+
|
90
|
+
This function returns the input for subprocess.run() to check the static types.
|
91
|
+
"""
|
92
|
+
return [*POETRY_RUN_ARGS, "mypy"]
|
93
|
+
|
94
|
+
|
95
|
+
def _security_checking() -> list[str | Path]:
|
96
|
+
"""Check the security of the code.
|
97
|
+
|
98
|
+
This function returns the input for subprocess.run() to check the security of
|
99
|
+
the code.
|
100
|
+
"""
|
101
|
+
return [*POETRY_RUN_ARGS, "bandit", "-c", "pyproject.toml", "-r", "."]
|
102
|
+
|
103
|
+
|
104
|
+
def _testing() -> list[str | Path]:
|
105
|
+
"""Run the tests.
|
106
|
+
|
107
|
+
This function returns the input for subprocess.run() to run all tests.
|
108
|
+
"""
|
109
|
+
return [*POETRY_RUN_ARGS, "pytest"]
|
@@ -0,0 +1,49 @@
|
|
1
|
+
"""Contains the pre-commit to run all hooks required by the winipedia_utils package.
|
2
|
+
|
3
|
+
This script is meant to be run by pre-commit (https://pre-commit.com/)
|
4
|
+
and should not be modified manually.
|
5
|
+
"""
|
6
|
+
|
7
|
+
import sys
|
8
|
+
|
9
|
+
from winipedia_utils.git.pre_commit import hooks
|
10
|
+
from winipedia_utils.logging.ansi import GREEN, RED, RESET
|
11
|
+
from winipedia_utils.logging.logger import get_logger
|
12
|
+
from winipedia_utils.modules.function import get_all_functions_from_module
|
13
|
+
from winipedia_utils.os.os import run_subprocess
|
14
|
+
|
15
|
+
logger = get_logger(__name__)
|
16
|
+
|
17
|
+
|
18
|
+
def _run_all_hooks() -> None:
|
19
|
+
"""Import all funcs defined in hooks.py and runs them."""
|
20
|
+
hook_funcs = get_all_functions_from_module(hooks)
|
21
|
+
|
22
|
+
exit_code = 0
|
23
|
+
for hook_func in hook_funcs:
|
24
|
+
subprocess_args = hook_func()
|
25
|
+
result = run_subprocess(
|
26
|
+
subprocess_args, check=False, capture_output=True, text=True
|
27
|
+
)
|
28
|
+
passed = result.returncode == 0
|
29
|
+
|
30
|
+
log_method = logger.info
|
31
|
+
passed_str = (f"{GREEN}PASSED" if passed else f"{RED}FAILED") + RESET
|
32
|
+
if not passed:
|
33
|
+
log_method = logger.error
|
34
|
+
passed_str += f"\n{result.stdout}"
|
35
|
+
exit_code = 1
|
36
|
+
# make the dashes always the same lentgth by adjusting to len of hook name
|
37
|
+
num_dashes = 50 - len(hook_func.__name__)
|
38
|
+
log_method(
|
39
|
+
"Hook %s -%s> %s",
|
40
|
+
hook_func.__name__,
|
41
|
+
"-" * num_dashes,
|
42
|
+
passed_str,
|
43
|
+
)
|
44
|
+
|
45
|
+
sys.exit(exit_code)
|
46
|
+
|
47
|
+
|
48
|
+
if __name__ == "__main__":
|
49
|
+
_run_all_hooks()
|
@@ -0,0 +1 @@
|
|
1
|
+
"""__init__ module for winipedia_utils.iterating."""
|
@@ -0,0 +1,29 @@
|
|
1
|
+
"""Iterating utilities for handling iterables.
|
2
|
+
|
3
|
+
This module provides utility functions for working with iterables,
|
4
|
+
including getting the length of an iterable with a default value.
|
5
|
+
These utilities help with iterable operations and manipulations.
|
6
|
+
"""
|
7
|
+
|
8
|
+
from collections.abc import Iterable
|
9
|
+
from typing import Any
|
10
|
+
|
11
|
+
|
12
|
+
def get_len_with_default(iterable: Iterable[Any], default: int | None = None) -> int:
|
13
|
+
"""Get the length of an iterable with a default value.
|
14
|
+
|
15
|
+
Args:
|
16
|
+
iterable: Iterable to get the length of
|
17
|
+
default: Default value to return if the iterable is empty
|
18
|
+
|
19
|
+
Returns:
|
20
|
+
Length of the iterable or the default value if the iterable is empty
|
21
|
+
|
22
|
+
"""
|
23
|
+
try:
|
24
|
+
return len(iterable) # type: ignore[arg-type]
|
25
|
+
except TypeError as e:
|
26
|
+
if default is None:
|
27
|
+
msg = "Can't get length of iterable and no default value provided"
|
28
|
+
raise TypeError(msg) from e
|
29
|
+
return default
|
@@ -0,0 +1 @@
|
|
1
|
+
"""__init__ module for winipedia_utils.logging."""
|
@@ -0,0 +1,64 @@
|
|
1
|
+
"""Logging configuration for winipedia_utils.
|
2
|
+
|
3
|
+
This module provides a standardized logging configuration dictionary that can be
|
4
|
+
used with Python's logging.config.dictConfig() to set up consistent logging
|
5
|
+
across the application. The configuration includes formatters, handlers, and
|
6
|
+
logger settings for different components.
|
7
|
+
"""
|
8
|
+
|
9
|
+
# This dictionary can be passed directly to logging.config.dictConfig().
|
10
|
+
# It sets up a single console handler that prints **all** log levels
|
11
|
+
# (DEBUG, INFO, WARNING, ERROR and CRITICAL) using one consistent format.
|
12
|
+
|
13
|
+
from typing import Any
|
14
|
+
|
15
|
+
LOGGING_CONFIG: dict[str, Any] = {
|
16
|
+
"version": 1, # Mandatory schema version for dictConfig
|
17
|
+
"disable_existing_loggers": False, # Keep any loggers already created elsewhere
|
18
|
+
# ---------------------------- #
|
19
|
+
# Define a single formatter #
|
20
|
+
# ---------------------------- #
|
21
|
+
"formatters": {
|
22
|
+
"standard": { # You can reference this formatter by name
|
23
|
+
"format": (
|
24
|
+
"%(asctime)s | " # • %(asctime)s human-readable timestamp
|
25
|
+
"%(levelname)-8s | " # • %(asctime)s human-readable timestamp
|
26
|
+
"%(filename)s:" # • %(filename)s source file where the call was made
|
27
|
+
"%(lineno)d | " # • %(lineno)d line number in that file
|
28
|
+
"%(message)s" # • %(message)s the log message itself
|
29
|
+
),
|
30
|
+
"datefmt": "%Y-%m-%d %H:%M:%S", # Override default timestamp style
|
31
|
+
},
|
32
|
+
},
|
33
|
+
# --------------------------- #
|
34
|
+
# Define the console output #
|
35
|
+
# --------------------------- #
|
36
|
+
"handlers": {
|
37
|
+
"console": {
|
38
|
+
"class": "logging.StreamHandler", # Send logs to sys.stderr
|
39
|
+
"level": "DEBUG", # Capture *everything* ≥ DEBUG
|
40
|
+
"formatter": "standard", # Use the formatter above
|
41
|
+
"stream": "ext://sys.stdout", # Emit to stdout instead of stderr
|
42
|
+
},
|
43
|
+
},
|
44
|
+
# ------------------------------------------------------- #
|
45
|
+
# Attach the handler to either the root logger or named #
|
46
|
+
# loggers. Below we set up the root so every message in #
|
47
|
+
# your application uses this setup automatically. #
|
48
|
+
# ------------------------------------------------------- #
|
49
|
+
"root": {
|
50
|
+
"level": "DEBUG", # Accept all levels from DEBUG upward
|
51
|
+
"handlers": ["console"], # Pipe them through the console handler
|
52
|
+
},
|
53
|
+
# ------------------------------------------------------- #
|
54
|
+
# Optionally, tweak individual libraries if they are #
|
55
|
+
# too noisy. For example, silence urllib3 INFO chatter. #
|
56
|
+
# ------------------------------------------------------- #
|
57
|
+
"loggers": {
|
58
|
+
"urllib3": {
|
59
|
+
"level": "WARNING", # Raise urllib3's threshold to WARNING
|
60
|
+
"handlers": ["console"],
|
61
|
+
"propagate": False, # Prevent double-logging to the root
|
62
|
+
},
|
63
|
+
},
|
64
|
+
}
|
@@ -0,0 +1,26 @@
|
|
1
|
+
"""Logger utilities for winipedia_utils.
|
2
|
+
|
3
|
+
This module provides functions for creating and configuring loggers
|
4
|
+
throughout the application. It applies the standardized logging configuration
|
5
|
+
defined in the config module to ensure consistent logging behavior.
|
6
|
+
"""
|
7
|
+
|
8
|
+
import logging
|
9
|
+
from logging.config import dictConfig
|
10
|
+
|
11
|
+
from winipedia_utils.logging.config import LOGGING_CONFIG
|
12
|
+
|
13
|
+
dictConfig(LOGGING_CONFIG)
|
14
|
+
|
15
|
+
|
16
|
+
def get_logger(name: str) -> logging.Logger:
|
17
|
+
"""Get a logger with the given name.
|
18
|
+
|
19
|
+
Args:
|
20
|
+
name: The name for the logger, typically __name__ from the calling module
|
21
|
+
|
22
|
+
Returns:
|
23
|
+
A configured logger instance with the specified name
|
24
|
+
|
25
|
+
"""
|
26
|
+
return logging.getLogger(name)
|
@@ -0,0 +1 @@
|
|
1
|
+
"""__init__ module for winipedia_utils.modules."""
|
@@ -0,0 +1,76 @@
|
|
1
|
+
"""Class utilities for introspection and manipulation.
|
2
|
+
|
3
|
+
This module provides utility functions for working with Python classes,
|
4
|
+
including extracting methods from classes and finding classes within modules.
|
5
|
+
These utilities are particularly useful for reflection, testing,
|
6
|
+
and dynamic code generation.
|
7
|
+
"""
|
8
|
+
|
9
|
+
import inspect
|
10
|
+
from collections.abc import Callable
|
11
|
+
from importlib import import_module
|
12
|
+
from types import ModuleType
|
13
|
+
from typing import Any
|
14
|
+
|
15
|
+
from winipedia_utils.modules.function import is_func
|
16
|
+
|
17
|
+
|
18
|
+
def get_all_methods_from_cls(
|
19
|
+
class_: type, *, exclude_parent_methods: bool = False
|
20
|
+
) -> list[Callable[..., Any]]:
|
21
|
+
"""Get all methods from a class.
|
22
|
+
|
23
|
+
Retrieves all methods (functions or methods) from a class. Can optionally
|
24
|
+
exclude methods inherited from parent classes.
|
25
|
+
|
26
|
+
Args:
|
27
|
+
class_: The class to extract methods from
|
28
|
+
exclude_parent_methods: If True, only include methods defined in this class,
|
29
|
+
excluding those inherited from parent classes
|
30
|
+
Returns:
|
31
|
+
A list of callable methods from the class
|
32
|
+
|
33
|
+
"""
|
34
|
+
from winipedia_utils.modules.module import get_def_line, get_module_of_obj
|
35
|
+
|
36
|
+
methods = [
|
37
|
+
(method, name) for name, method in inspect.getmembers(class_) if is_func(method)
|
38
|
+
]
|
39
|
+
|
40
|
+
if exclude_parent_methods:
|
41
|
+
methods = [
|
42
|
+
(method, name)
|
43
|
+
for method, name in methods
|
44
|
+
if get_module_of_obj(method).__name__ == class_.__module__
|
45
|
+
and name in class_.__dict__
|
46
|
+
]
|
47
|
+
|
48
|
+
only_methods = [method for method, _name in methods]
|
49
|
+
# sort by definition order
|
50
|
+
return sorted(only_methods, key=get_def_line)
|
51
|
+
|
52
|
+
|
53
|
+
def get_all_cls_from_module(module: ModuleType | str) -> list[type]:
|
54
|
+
"""Get all classes defined in a module.
|
55
|
+
|
56
|
+
Retrieves all class objects that are defined directly in the specified module,
|
57
|
+
excluding imported classes.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
module: The module to extract classes from
|
61
|
+
|
62
|
+
Returns:
|
63
|
+
A list of class types defined in the module
|
64
|
+
|
65
|
+
"""
|
66
|
+
from winipedia_utils.modules.module import get_def_line, get_module_of_obj
|
67
|
+
|
68
|
+
if isinstance(module, str):
|
69
|
+
module = import_module(module)
|
70
|
+
classes = [
|
71
|
+
obj
|
72
|
+
for _, obj in inspect.getmembers(module, inspect.isclass)
|
73
|
+
if get_module_of_obj(obj).__name__ == module.__name__
|
74
|
+
]
|
75
|
+
# sort by definition order
|
76
|
+
return sorted(classes, key=get_def_line)
|
@@ -0,0 +1,86 @@
|
|
1
|
+
"""Function utilities for introspection and manipulation.
|
2
|
+
|
3
|
+
This module provides utility functions for working with Python functions,
|
4
|
+
including extracting functions from modules and manipulating function objects.
|
5
|
+
These utilities are particularly useful for reflection, testing, and
|
6
|
+
dynamic code generation.
|
7
|
+
"""
|
8
|
+
|
9
|
+
import inspect
|
10
|
+
from collections.abc import Callable
|
11
|
+
from importlib import import_module
|
12
|
+
from types import ModuleType
|
13
|
+
from typing import Any
|
14
|
+
|
15
|
+
|
16
|
+
def is_func_or_method(obj: Any) -> bool:
|
17
|
+
"""Return True if *obj* is a function or method.
|
18
|
+
|
19
|
+
This function checks if the given object is a function or method,
|
20
|
+
including those defined in a class body.
|
21
|
+
|
22
|
+
Args:
|
23
|
+
obj: The object to check
|
24
|
+
|
25
|
+
Returns:
|
26
|
+
bool: True if the object is a function or method, False otherwise
|
27
|
+
|
28
|
+
"""
|
29
|
+
return inspect.isfunction(obj) or inspect.ismethod(obj)
|
30
|
+
|
31
|
+
|
32
|
+
def is_func(obj: Any) -> bool:
|
33
|
+
"""Return True if *obj* is a 'method-like' attribute as it appears in a class body.
|
34
|
+
|
35
|
+
Accepts:
|
36
|
+
|
37
|
+
|
38
|
+
• plain functions (instance methods)
|
39
|
+
• staticmethod / classmethod descriptors
|
40
|
+
• property descriptors (getter counts as method)
|
41
|
+
• decorated functions that keep a __wrapped__ chain
|
42
|
+
|
43
|
+
Returns:
|
44
|
+
bool: True if the object is a method-like attribute, False otherwise
|
45
|
+
|
46
|
+
"""
|
47
|
+
# plain function
|
48
|
+
|
49
|
+
if is_func_or_method(obj):
|
50
|
+
return True
|
51
|
+
|
52
|
+
if isinstance(obj, (staticmethod, classmethod, property)):
|
53
|
+
return True
|
54
|
+
|
55
|
+
# unwrap any wrappers (@functools.wraps) and retest
|
56
|
+
|
57
|
+
unwrapped = inspect.unwrap(obj)
|
58
|
+
|
59
|
+
return is_func_or_method(unwrapped)
|
60
|
+
|
61
|
+
|
62
|
+
def get_all_functions_from_module(module: ModuleType | str) -> list[Callable[..., Any]]:
|
63
|
+
"""Get all functions defined in a module.
|
64
|
+
|
65
|
+
Retrieves all function objects that are defined directly in the specified module,
|
66
|
+
excluding imported functions.
|
67
|
+
The functions are sorted by their line number in the module.
|
68
|
+
|
69
|
+
Args:
|
70
|
+
module: The module to extract functions from
|
71
|
+
|
72
|
+
Returns:
|
73
|
+
A list of callable functions defined in the module
|
74
|
+
|
75
|
+
"""
|
76
|
+
from winipedia_utils.modules.module import get_def_line, get_module_of_obj
|
77
|
+
|
78
|
+
if isinstance(module, str):
|
79
|
+
module = import_module(module)
|
80
|
+
funcs = [
|
81
|
+
func
|
82
|
+
for _name, func in inspect.getmembers(module, is_func)
|
83
|
+
if get_module_of_obj(func).__name__ == module.__name__
|
84
|
+
]
|
85
|
+
# sort by definition order
|
86
|
+
return sorted(funcs, key=get_def_line)
|