From d596dd433051aafd938c36f9e00d4d56c6108254 Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 15:56:56 +0100 Subject: [PATCH 01/10] Re-migrate with script only --- config/coverage.ini | 2 +- config/ruff.toml | 12 +- duties.py | 2 +- packages/griffecli/pyproject.toml | 48 ++ packages/griffecli/src/griffecli/__init__.py | 1 + packages/griffecli/src/griffecli/__main__.py | 13 + .../griffecli/src/griffecli}/_internal/cli.py | 22 +- packages/griffelib/pyproject.toml | 48 ++ packages/griffelib/src/griffelib/__init__.py | 642 +++++++++++++++++ .../src/griffelib}/_internal/__init__.py | 0 .../griffelib}/_internal/agents/__init__.py | 0 .../griffelib}/_internal/agents/inspector.py | 20 +- .../_internal/agents/nodes/__init__.py | 0 .../_internal/agents/nodes/assignments.py | 0 .../griffelib}/_internal/agents/nodes/ast.py | 2 +- .../_internal/agents/nodes/docstrings.py | 0 .../_internal/agents/nodes/exports.py | 10 +- .../_internal/agents/nodes/imports.py | 2 +- .../_internal/agents/nodes/parameters.py | 2 +- .../_internal/agents/nodes/runtime.py | 4 +- .../_internal/agents/nodes/values.py | 2 +- .../griffelib}/_internal/agents/visitor.py | 28 +- .../src/griffelib}/_internal/c3linear.py | 0 .../src/griffelib}/_internal/collections.py | 4 +- .../src/griffelib}/_internal/debug.py | 0 .../src/griffelib}/_internal/diff.py | 18 +- .../_internal/docstrings/__init__.py | 0 .../griffelib}/_internal/docstrings/auto.py | 18 +- .../griffelib}/_internal/docstrings/google.py | 10 +- .../griffelib}/_internal/docstrings/models.py | 6 +- .../griffelib}/_internal/docstrings/numpy.py | 12 +- .../_internal/docstrings/parsers.py | 14 +- .../griffelib}/_internal/docstrings/sphinx.py | 8 +- .../griffelib}/_internal/docstrings/utils.py | 12 +- .../src/griffelib}/_internal/encoders.py | 14 +- .../src/griffelib}/_internal/enumerations.py | 0 .../src/griffelib}/_internal/exceptions.py | 2 +- .../src/griffelib}/_internal/expressions.py | 10 +- .../_internal/extensions/__init__.py | 0 .../griffelib}/_internal/extensions/base.py | 18 +- .../_internal/extensions/dataclasses.py | 10 +- .../_internal/extensions/unpack_typeddict.py | 10 +- .../src/griffelib}/_internal/finder.py | 16 +- .../griffelib/src/griffelib}/_internal/git.py | 4 +- .../src/griffelib}/_internal/importer.py | 0 .../src/griffelib}/_internal/loader.py | 40 +- .../src/griffelib}/_internal/logger.py | 2 +- .../src/griffelib}/_internal/merger.py | 6 +- .../src/griffelib}/_internal/mixins.py | 12 +- .../src/griffelib}/_internal/models.py | 38 +- .../src/griffelib}/_internal/py.typed | 0 .../src/griffelib}/_internal/stats.py | 6 +- .../src/griffelib}/_internal/tests.py | 18 +- pyproject.toml | 2 +- scripts/griffe_exts.py | 10 +- src/griffe/__init__.py | 646 +----------------- src/griffe/__main__.py | 9 +- tests/helpers.py | 2 +- tests/test_api.py | 46 +- tests/test_cli.py | 2 +- tests/test_diff.py | 2 +- tests/test_docstrings/conftest.py | 2 +- tests/test_docstrings/helpers.py | 2 +- tests/test_docstrings/test_google.py | 2 +- tests/test_docstrings/test_numpy.py | 2 +- tests/test_docstrings/test_sphinx.py | 2 +- tests/test_docstrings/test_warnings.py | 2 +- tests/test_encoders.py | 2 +- tests/test_expressions.py | 2 +- tests/test_extensions/test_base.py | 6 +- tests/test_extensions/test_dataclasses.py | 2 +- .../test_extensions/test_unpack_typeddict.py | 2 +- tests/test_finder.py | 8 +- tests/test_functions.py | 2 +- tests/test_git.py | 4 +- tests/test_inheritance.py | 4 +- tests/test_inspector.py | 2 +- tests/test_loader.py | 4 +- tests/test_merger.py | 2 +- tests/test_mixins.py | 2 +- tests/test_models.py | 2 +- tests/test_nodes.py | 2 +- tests/test_public_api.py | 2 +- tests/test_stdlib.py | 4 +- tests/test_visitor.py | 2 +- 85 files changed, 1032 insertions(+), 921 deletions(-) create mode 100644 packages/griffecli/pyproject.toml create mode 100644 packages/griffecli/src/griffecli/__init__.py create mode 100644 packages/griffecli/src/griffecli/__main__.py rename {src/griffe => packages/griffecli/src/griffecli}/_internal/cli.py (96%) create mode 100644 packages/griffelib/pyproject.toml create mode 100644 packages/griffelib/src/griffelib/__init__.py rename {src/griffe => packages/griffelib/src/griffelib}/_internal/__init__.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/__init__.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/inspector.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/__init__.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/assignments.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/ast.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/docstrings.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/exports.py (92%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/imports.py (95%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/parameters.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/runtime.py (99%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/nodes/values.py (96%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/agents/visitor.py (96%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/c3linear.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/collections.py (94%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/debug.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/diff.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/__init__.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/auto.py (93%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/google.py (99%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/models.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/numpy.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/parsers.py (72%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/sphinx.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/docstrings/utils.py (88%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/encoders.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/enumerations.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/exceptions.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/expressions.py (99%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/extensions/__init__.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/extensions/base.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/extensions/dataclasses.py (96%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/extensions/unpack_typeddict.py (96%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/finder.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/git.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/importer.py (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/loader.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/logger.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/merger.py (95%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/mixins.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/models.py (98%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/py.typed (100%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/stats.py (97%) rename {src/griffe => packages/griffelib/src/griffelib}/_internal/tests.py (96%) diff --git a/config/coverage.ini b/config/coverage.ini index 7db748bfd..6f57222a8 100644 --- a/config/coverage.ini +++ b/config/coverage.ini @@ -2,7 +2,7 @@ branch = true parallel = true source = - src/griffe + packages/griffe/src/griffe tests/ [coverage:paths] diff --git a/config/ruff.toml b/config/ruff.toml index 0a52cb729..5624a49e7 100644 --- a/config/ruff.toml +++ b/config/ruff.toml @@ -38,24 +38,24 @@ ignore = [ logger-objects = ["griffe.logger"] [lint.per-file-ignores] -"src/griffe/__main__.py" = [ +"packages/griffe/src/griffe/__main__.py" = [ "D100", # Missing module docstring ] -"src/griffe/_internal/cli.py" = [ +"packages/griffe/src/griffe/_internal/cli.py" = [ "T201", # Print statement ] -"src/griffe/_internal/git.py" = [ +"packages/griffe/src/griffe/_internal/git.py" = [ "S603", # `subprocess` call: check for execution of untrusted input "S607", # Starting a process with a partial executable path ] -"src/griffe/_internal/agents/nodes/*.py" = [ +"packages/griffe/src/griffe/_internal/agents/nodes/*.py" = [ "ARG001", # Unused function argument "N812", # Lowercase `keyword` imported as non-lowercase `NodeKeyword` ] -"src/griffe/_internal/debug.py" = [ +"packages/griffe/src/griffe/_internal/debug.py" = [ "T201", # Print statement ] -"src/griffe/_internal/**.py" = [ +"packages/griffe/src/griffe/_internal/**.py" = [ "D100", # Missing docstring in public module ] "scripts/*.py" = [ diff --git a/duties.py b/duties.py index 21fc7fccb..2434398c8 100644 --- a/duties.py +++ b/duties.py @@ -498,7 +498,7 @@ def fuzz( min_seed: Minimum value for the seeds range. max_seed: Maximum value for the seeds range. """ - from griffe import visit # noqa: PLC0415 + from griffelib import visit # noqa: PLC0415 warnings.simplefilter("ignore", SyntaxWarning) diff --git a/packages/griffecli/pyproject.toml b/packages/griffecli/pyproject.toml new file mode 100644 index 000000000..cf6e80d23 --- /dev/null +++ b/packages/griffecli/pyproject.toml @@ -0,0 +1,48 @@ +[build-system] +# pdm-backend is left here as a dependency of the version discovery script currently in use. +# It may be removed in the future. See mkdocstrings/griffe#430 +requires = ["hatchling", "pdm-backend", "uv-dynamic-versioning>=0.7.0"] +build-backend = "hatchling.build" + +[tool.hatch.version] +source = "code" +path = "../../scripts/get_version.py" +expression = "get_version()" + +[project] +name = "griffecli" +description = "The griffelib CLI" +authors = [{name = "Timothée Mazzucotelli", email = "dev@pawamoy.fr"}] +license = "ISC" +license-files = ["LICENSE"] +requires-python = ">=3.10" +keywords = ["api", "signature", "breaking-changes", "static-analysis", "dynamic-analysis"] +dynamic = ["version", "dependencies", "optional-dependencies"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + # YORE: EOL 3.10: Remove line. + "Programming Language :: Python :: 3.10", + # YORE: EOL 3.11: Remove line. + "Programming Language :: Python :: 3.11", + # YORE: EOL 3.12: Remove line. + "Programming Language :: Python :: 3.12", + # YORE: EOL 3.13: Remove line. + "Programming Language :: Python :: 3.13", + # YORE: EOL 3.14: Remove line. + "Programming Language :: Python :: 3.14", + "Topic :: Documentation", + "Topic :: Software Development", + "Topic :: Software Development :: Documentation", + "Topic :: Utilities", + "Typing :: Typed", +] + +[tool.hatch.metadata.hooks.uv-dynamic-versioning] + +[tool.hatch.metadata.hooks.uv-dynamic-versioning.optional-dependencies] + +[tool.hatch.build.targets.sdist] diff --git a/packages/griffecli/src/griffecli/__init__.py b/packages/griffecli/src/griffecli/__init__.py new file mode 100644 index 000000000..54cec7a60 --- /dev/null +++ b/packages/griffecli/src/griffecli/__init__.py @@ -0,0 +1 @@ +# TODO: Cut proper imports from griffelib `__init__.py` module diff --git a/packages/griffecli/src/griffecli/__main__.py b/packages/griffecli/src/griffecli/__main__.py new file mode 100644 index 000000000..0bd485571 --- /dev/null +++ b/packages/griffecli/src/griffecli/__main__.py @@ -0,0 +1,13 @@ +# Entry-point module, in case you use `python -m griffe`. +# +# Why does this file exist, and why `__main__`? For more info, read: +# +# - https://www.python.org/dev/peps/pep-0338/ +# - https://docs.python.org/3/using/cmdline.html#cmdoption-m + +import sys + +from griffecli._internal.cli import main + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/src/griffe/_internal/cli.py b/packages/griffecli/src/griffecli/_internal/cli.py similarity index 96% rename from src/griffe/_internal/cli.py rename to packages/griffecli/src/griffecli/_internal/cli.py index 1f6c767f5..877d8db89 100644 --- a/src/griffe/_internal/cli.py +++ b/packages/griffecli/src/griffecli/_internal/cli.py @@ -24,21 +24,21 @@ import colorama -from griffe._internal import debug -from griffe._internal.diff import find_breaking_changes -from griffe._internal.encoders import JSONEncoder -from griffe._internal.enumerations import ExplanationStyle, Parser -from griffe._internal.exceptions import ExtensionError, GitError -from griffe._internal.extensions.base import load_extensions -from griffe._internal.git import _get_latest_tag, _get_repo_root -from griffe._internal.loader import GriffeLoader, load, load_git, load_pypi -from griffe._internal.logger import logger +from griffelib._internal import debug +from griffelib._internal.diff import find_breaking_changes +from griffelib._internal.encoders import JSONEncoder +from griffelib._internal.enumerations import ExplanationStyle, Parser +from griffelib._internal.exceptions import ExtensionError, GitError +from griffelib._internal.extensions.base import load_extensions +from griffelib._internal.git import _get_latest_tag, _get_repo_root +from griffelib._internal.loader import GriffeLoader, load, load_git, load_pypi +from griffelib._internal.logger import logger if TYPE_CHECKING: from collections.abc import Sequence - from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle - from griffe._internal.extensions.base import Extension, Extensions + from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle + from griffelib._internal.extensions.base import Extension, Extensions DEFAULT_LOG_LEVEL = os.getenv("GRIFFE_LOG_LEVEL", "INFO").upper() diff --git a/packages/griffelib/pyproject.toml b/packages/griffelib/pyproject.toml new file mode 100644 index 000000000..280d86cfe --- /dev/null +++ b/packages/griffelib/pyproject.toml @@ -0,0 +1,48 @@ +[build-system] +# pdm-backend is left here as a dependency of the version discovery script currently in use. +# It may be removed in the future. See mkdocstrings/griffe#430 +requires = ["hatchling", "pdm-backend", "uv-dynamic-versioning>=0.7.0"] +build-backend = "hatchling.build" + +[tool.hatch.version] +source = "code" +path = "../../scripts/get_version.py" +expression = "get_version()" + +[project] +name = "griffe" +description = "The griffelib library" +authors = [{name = "Timothée Mazzucotelli", email = "dev@pawamoy.fr"}] +license = "ISC" +license-files = ["LICENSE"] +requires-python = ">=3.10" +keywords = ["api", "signature", "breaking-changes", "static-analysis", "dynamic-analysis"] +dynamic = ["version", "dependencies", "optional-dependencies"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + # YORE: EOL 3.10: Remove line. + "Programming Language :: Python :: 3.10", + # YORE: EOL 3.11: Remove line. + "Programming Language :: Python :: 3.11", + # YORE: EOL 3.12: Remove line. + "Programming Language :: Python :: 3.12", + # YORE: EOL 3.13: Remove line. + "Programming Language :: Python :: 3.13", + # YORE: EOL 3.14: Remove line. + "Programming Language :: Python :: 3.14", + "Topic :: Documentation", + "Topic :: Software Development", + "Topic :: Software Development :: Documentation", + "Topic :: Utilities", + "Typing :: Typed", +] + +[tool.hatch.metadata.hooks.uv-dynamic-versioning] + +[tool.hatch.metadata.hooks.uv-dynamic-versioning.optional-dependencies] + +[tool.hatch.build.targets.sdist] diff --git a/packages/griffelib/src/griffelib/__init__.py b/packages/griffelib/src/griffelib/__init__.py new file mode 100644 index 000000000..8b93293da --- /dev/null +++ b/packages/griffelib/src/griffelib/__init__.py @@ -0,0 +1,642 @@ +# This top-level module imports all public names from the package, +# and exposes them as public objects. We have tests to make sure +# no object is forgotten in this list. + +"""Griffe package. + +Signatures for entire Python programs. +Extract the structure, the frame, the skeleton of your project, +to generate API documentation or find breaking changes in your API. + +The entirety of the public API is exposed here, in the top-level `griffe` module. + +All messages written to standard output or error are logged using the `logging` module. +Our logger's name is set to `"griffe"` and is public (you can rely on it). +You can obtain the logger from the standard `logging` module: `logging.getLogger("griffe")`. +Actual logging messages are not part of the public API (they might change without notice). + +Raised exceptions throughout the package are part of the public API (you can rely on them). +Their actual messages are not part of the public API (they might change without notice). + +The following paragraphs will help you discover the package's content. + +## CLI entrypoints + +Griffe provides a command-line interface (CLI) to interact with the package. The CLI entrypoints can be called from Python code. + +- [`griffe.main`][]: Run the main program. +- [`griffe.check`][]: Check for API breaking changes in two versions of the same package. +- [`griffe.dump`][]: Load packages data and dump it as JSON. + +## Loaders + +To load API data, Griffe provides several high-level functions. + +- [`griffe.load`][]: Load and return a Griffe object. +- [`griffe.load_git`][]: Load and return a module from a specific Git reference. +- [`griffe.load_pypi`][]: Load and return a module from a specific package version downloaded using pip. + +## Models + +The data loaded by Griffe is represented by several classes. + +- [`griffe.Module`][]: The class representing a Python module. +- [`griffe.Class`][]: The class representing a Python class. +- [`griffe.Function`][]: The class representing a Python function or method. +- [`griffe.Attribute`][]: The class representing a Python attribute. +- [`griffe.Alias`][]: This class represents an alias, or indirection, to an object declared in another module. + +Additional classes are available to represent other concepts. + +- [`griffe.Decorator`][]: This class represents a decorator. +- [`griffe.Parameters`][]: This class is a container for parameters. +- [`griffe.Parameter`][]: This class represent a function parameter. + +## Agents + +Griffe is able to analyze code both statically and dynamically, using the following "agents". +However most of the time you will only need to use the loaders above. + +- [`griffe.visit`][]: Parse and visit a module file. +- [`griffe.inspect`][]: Inspect a module. + +## Serializers + +Griffe can serizalize data to dictionary and JSON. + +- [`griffe.Object.as_json`][griffe.Object.as_json] +- [`griffe.Object.from_json`][griffe.Object.from_json] +- [`griffe.JSONEncoder`][]: JSON encoder for Griffe objects. +- [`griffe.json_decoder`][]: JSON decoder for Griffe objects. + +## API checks + +Griffe can compare two versions of the same package to find breaking changes. + +- [`griffe.find_breaking_changes`][]: Find breaking changes between two versions of the same API. +- [`griffe.Breakage`][]: Breakage classes can explain what broke from a version to another. + +## Extensions + +Griffe supports extensions. You can create your own extension by subclassing the `griffe.Extension` class. + +- [`griffe.load_extensions`][]: Load configured extensions. +- [`griffe.Extension`][]: Base class for Griffe extensions. + +## Docstrings + +Griffe can parse docstrings into structured data. + +Main class: + +- [`griffe.Docstring`][]: This class represents docstrings. + +Docstring section and element classes all start with `Docstring`. + +Docstring parsers: + +- [`griffe.parse`][]: Parse the docstring. +- [`griffe.parse_auto`][]: Parse a docstring by automatically detecting the style it uses. +- [`griffe.parse_google`][]: Parse a Google-style docstring. +- [`griffe.parse_numpy`][]: Parse a Numpydoc-style docstring. +- [`griffe.parse_sphinx`][]: Parse a Sphinx-style docstring. + +## Exceptions + +Griffe uses several exceptions to signal errors. + +- [`griffe.GriffeError`][]: The base exception for all Griffe errors. +- [`griffe.LoadingError`][]: Exception for loading errors. +- [`griffe.NameResolutionError`][]: Exception for names that cannot be resolved in a object scope. +- [`griffe.UnhandledEditableModuleError`][]: Exception for unhandled editables modules, when searching modules. +- [`griffe.UnimportableModuleError`][]: Exception for modules that cannot be imported. +- [`griffe.AliasResolutionError`][]: Exception for aliases that cannot be resolved. +- [`griffe.CyclicAliasError`][]: Exception raised when a cycle is detected in aliases. +- [`griffe.LastNodeError`][]: Exception raised when trying to access a next or previous node. +- [`griffe.RootNodeError`][]: Exception raised when trying to use siblings properties on a root node. +- [`griffe.BuiltinModuleError`][]: Exception raised when trying to access the filepath of a builtin module. +- [`griffe.ExtensionError`][]: Base class for errors raised by extensions. +- [`griffe.ExtensionNotLoadedError`][]: Exception raised when an extension could not be loaded. +- [`griffe.GitError`][]: Exception raised for errors related to Git. + +# Expressions + +Griffe stores snippets of code (attribute values, decorators, base class, type annotations) as expressions. +Expressions are basically abstract syntax trees (AST) with a few differences compared to the nodes returned by [`ast`][]. +Griffe provides a few helpers to extract expressions from regular AST nodes. + +- [`griffe.get_annotation`][]: Get a type annotation as expression. +- [`griffe.get_base_class`][]: Get a base class as expression. +- [`griffe.get_class_keyword`][]: Get a class keyword as expression. +- [`griffe.get_condition`][]: Get a condition as expression. +- [`griffe.get_expression`][]: Get an expression from an AST node. +- [`griffe.safe_get_annotation`][]: Get a type annotation as expression, safely (returns `None` on error). +- [`griffe.safe_get_base_class`][]: Get a base class as expression, safely (returns `None` on error). +- [`griffe.safe_get_class_keyword`][]: Get a class keyword as expression, safely (returns `None` on error). +- [`griffe.safe_get_condition`][]: Get a condition as expression, safely (returns `None` on error). +- [`griffe.safe_get_expression`][]: Get an expression from an AST node, safely (returns `None` on error). + +The base class for expressions. + +- [`griffe.Expr`][] + +Expression classes all start with `Expr`. + +# Loggers + +If you want to log messages from extensions, get a logger with `get_logger`. +The `logger` attribute is used by Griffe itself. You can use it to temporarily disable Griffe logging. + +- [`griffe.logger`][]: Our global logger, used throughout the library. +- [`griffe.get_logger`][]: Create and return a new logger instance. + +# Helpers + +To test your Griffe extensions, or to load API data from code in memory, Griffe provides the following helpers. + +- [`griffe.temporary_pyfile`][]: Create a Python file containing the given code in a temporary directory. +- [`griffe.temporary_pypackage`][]: Create a package containing the given modules in a temporary directory. +- [`griffe.temporary_visited_module`][]: Create and visit a temporary module with the given code. +- [`griffe.temporary_visited_package`][]: Create and visit a temporary package. +- [`griffe.temporary_inspected_module`][]: Create and inspect a temporary module with the given code. +- [`griffe.temporary_inspected_package`][]: Create and inspect a temporary package. +""" + +from __future__ import annotations + +import warnings +from typing import Any + +from griffelib._internal.agents.inspector import Inspector, inspect +from griffelib._internal.agents.nodes.assignments import get_instance_names, get_name, get_names +from griffelib._internal.agents.nodes.ast import ( + ast_children, + ast_first_child, + ast_kind, + ast_last_child, + ast_next, + ast_next_siblings, + ast_previous, + ast_previous_siblings, + ast_siblings, +) +from griffelib._internal.agents.nodes.docstrings import get_docstring + +# YORE: Bump 2: Replace `ExportedName, ` with `` within line. +from griffelib._internal.agents.nodes.exports import ExportedName, get__all__, safe_get__all__ +from griffelib._internal.agents.nodes.imports import relative_to_absolute +from griffelib._internal.agents.nodes.parameters import ParametersType, get_parameters +from griffelib._internal.agents.nodes.runtime import ObjectNode +from griffelib._internal.agents.nodes.values import get_value, safe_get_value +from griffelib._internal.agents.visitor import Visitor, builtin_decorators, stdlib_decorators, typing_overload, visit +from griffelib._internal.c3linear import c3linear_merge +from griffecli._internal.cli import DEFAULT_LOG_LEVEL, check, dump, get_parser, main +from griffelib._internal.collections import LinesCollection, ModulesCollection +from griffelib._internal.diff import ( + AttributeChangedTypeBreakage, + AttributeChangedValueBreakage, + Breakage, + ClassRemovedBaseBreakage, + ObjectChangedKindBreakage, + ObjectRemovedBreakage, + ParameterAddedRequiredBreakage, + ParameterChangedDefaultBreakage, + ParameterChangedKindBreakage, + ParameterChangedRequiredBreakage, + ParameterMovedBreakage, + ParameterRemovedBreakage, + ReturnChangedTypeBreakage, + find_breaking_changes, +) +from griffelib._internal.docstrings.auto import ( + AutoOptions, + DocstringDetectionMethod, + PerStyleOptions, + infer_docstring_style, + parse_auto, +) +from griffelib._internal.docstrings.google import GoogleOptions, parse_google +from griffelib._internal.docstrings.models import ( + DocstringAdmonition, + DocstringAttribute, + DocstringClass, + DocstringDeprecated, + DocstringElement, + DocstringFunction, + DocstringModule, + DocstringNamedElement, + DocstringParameter, + DocstringRaise, + DocstringReceive, + DocstringReturn, + DocstringSection, + DocstringSectionAdmonition, + DocstringSectionAttributes, + DocstringSectionClasses, + DocstringSectionDeprecated, + DocstringSectionExamples, + DocstringSectionFunctions, + DocstringSectionModules, + DocstringSectionOtherParameters, + DocstringSectionParameters, + DocstringSectionRaises, + DocstringSectionReceives, + DocstringSectionReturns, + DocstringSectionText, + DocstringSectionTypeAliases, + DocstringSectionTypeParameters, + DocstringSectionWarns, + DocstringSectionYields, + DocstringTypeAlias, + DocstringTypeParameter, + DocstringWarn, + DocstringYield, +) +from griffelib._internal.docstrings.numpy import NumpyOptions, parse_numpy +from griffelib._internal.docstrings.parsers import ( + DocstringOptions, + DocstringStyle, + parse, + parsers, +) +from griffelib._internal.docstrings.sphinx import SphinxOptions, parse_sphinx +from griffelib._internal.docstrings.utils import docstring_warning, parse_docstring_annotation +from griffelib._internal.encoders import JSONEncoder, json_decoder +from griffelib._internal.enumerations import ( + BreakageKind, + DocstringSectionKind, + ExplanationStyle, + Kind, + LogLevel, + ObjectKind, + ParameterKind, + Parser, + TypeParameterKind, +) +from griffelib._internal.exceptions import ( + AliasResolutionError, + BuiltinModuleError, + CyclicAliasError, + ExtensionError, + ExtensionNotLoadedError, + GitError, + GriffeError, + LastNodeError, + LoadingError, + NameResolutionError, + RootNodeError, + UnhandledEditableModuleError, + UnimportableModuleError, +) +from griffelib._internal.expressions import ( + Expr, + ExprAttribute, + ExprBinOp, + ExprBoolOp, + ExprCall, + ExprCompare, + ExprComprehension, + ExprConstant, + ExprDict, + ExprDictComp, + ExprExtSlice, + ExprFormatted, + ExprGeneratorExp, + ExprIfExp, + ExprJoinedStr, + ExprKeyword, + ExprLambda, + ExprList, + ExprListComp, + ExprName, + ExprNamedExpr, + ExprParameter, + ExprSet, + ExprSetComp, + ExprSlice, + ExprSubscript, + ExprTuple, + ExprUnaryOp, + ExprVarKeyword, + ExprVarPositional, + ExprYield, + ExprYieldFrom, + get_annotation, + get_base_class, + get_class_keyword, + get_condition, + get_expression, + safe_get_annotation, + safe_get_base_class, + safe_get_class_keyword, + safe_get_condition, + safe_get_expression, +) +from griffelib._internal.extensions.base import ( + Extension, + Extensions, + LoadableExtensionType, + builtin_extensions, + load_extensions, +) +from griffelib._internal.extensions.dataclasses import DataclassesExtension +from griffelib._internal.extensions.unpack_typeddict import UnpackTypedDictExtension +from griffelib._internal.finder import ModuleFinder, NamePartsAndPathType, NamePartsType, NamespacePackage, Package +from griffelib._internal.git import GitInfo, KnownGitService +from griffelib._internal.importer import dynamic_import, sys_path +from griffelib._internal.loader import GriffeLoader, load, load_git, load_pypi +from griffelib._internal.logger import Logger, get_logger, logger, patch_loggers +from griffelib._internal.merger import merge_stubs +from griffelib._internal.mixins import ( + DelMembersMixin, + GetMembersMixin, + ObjectAliasMixin, + SerializationMixin, + SetMembersMixin, +) +from griffelib._internal.models import ( + Alias, + Attribute, + Class, + Decorator, + Docstring, + Function, + Module, + Object, + Parameter, + Parameters, + TypeAlias, + TypeParameter, + TypeParameters, +) +from griffelib._internal.stats import Stats +from griffelib._internal.tests import ( + TmpPackage, + htree, + module_vtree, + temporary_inspected_module, + temporary_inspected_package, + temporary_pyfile, + temporary_pypackage, + temporary_visited_module, + temporary_visited_package, + vtree, +) + +# YORE: Bump 2: Remove block. +_deprecated_names = ( + "assert_git_repo", + "get_latest_tag", + "get_repo_root", + "tmp_worktree", +) + + +# YORE: Bump 2: Remove block. +def __getattr__(name: str) -> Any: + if name in _deprecated_names: + from griffelib._internal import git # noqa: PLC0415 + + warnings.warn( + f"The `{name}` function is deprecated and will become unavailable in the next major version.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(git, f"_{name}") + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +# Regenerate this list with the following Python snippet: +# import griffelib +# names = sorted(n for n in dir(griffe) if not n.startswith("_") and n not in ("Any", "annotations", "lazy_importing", "warnings")) +# print('__all__ = [\n "' + '",\n "'.join(names) + '",\n]') +__all__ = [ + "DEFAULT_LOG_LEVEL", + "Alias", + "AliasResolutionError", + "Attribute", + "AttributeChangedTypeBreakage", + "AttributeChangedValueBreakage", + "AutoOptions", + "Breakage", + "BreakageKind", + "BuiltinModuleError", + "Class", + "ClassRemovedBaseBreakage", + "CyclicAliasError", + "DataclassesExtension", + "Decorator", + "DelMembersMixin", + "Docstring", + "DocstringAdmonition", + "DocstringAttribute", + "DocstringClass", + "DocstringDeprecated", + "DocstringDetectionMethod", + "DocstringElement", + "DocstringFunction", + "DocstringModule", + "DocstringNamedElement", + "DocstringOptions", + "DocstringParameter", + "DocstringRaise", + "DocstringReceive", + "DocstringReturn", + "DocstringSection", + "DocstringSectionAdmonition", + "DocstringSectionAttributes", + "DocstringSectionClasses", + "DocstringSectionDeprecated", + "DocstringSectionExamples", + "DocstringSectionFunctions", + "DocstringSectionKind", + "DocstringSectionModules", + "DocstringSectionOtherParameters", + "DocstringSectionParameters", + "DocstringSectionRaises", + "DocstringSectionReceives", + "DocstringSectionReturns", + "DocstringSectionText", + "DocstringSectionTypeAliases", + "DocstringSectionTypeParameters", + "DocstringSectionWarns", + "DocstringSectionYields", + "DocstringStyle", + "DocstringTypeAlias", + "DocstringTypeParameter", + "DocstringWarn", + "DocstringYield", + "ExplanationStyle", + # YORE: Bump 2: Remove line. + "ExportedName", + "Expr", + "ExprAttribute", + "ExprBinOp", + "ExprBoolOp", + "ExprCall", + "ExprCompare", + "ExprComprehension", + "ExprConstant", + "ExprDict", + "ExprDictComp", + "ExprExtSlice", + "ExprFormatted", + "ExprGeneratorExp", + "ExprIfExp", + "ExprJoinedStr", + "ExprKeyword", + "ExprLambda", + "ExprList", + "ExprListComp", + "ExprName", + "ExprNamedExpr", + "ExprParameter", + "ExprSet", + "ExprSetComp", + "ExprSlice", + "ExprSubscript", + "ExprTuple", + "ExprUnaryOp", + "ExprVarKeyword", + "ExprVarPositional", + "ExprYield", + "ExprYieldFrom", + "Extension", + "ExtensionError", + "ExtensionNotLoadedError", + "Extensions", + "Function", + "GetMembersMixin", + "GitError", + "GitInfo", + "GoogleOptions", + "GriffeError", + "GriffeLoader", + "Inspector", + "JSONEncoder", + "Kind", + "KnownGitService", + "LastNodeError", + "LinesCollection", + "LoadableExtensionType", + "LoadingError", + "LogLevel", + "Logger", + "Module", + "ModuleFinder", + "ModulesCollection", + "NamePartsAndPathType", + "NamePartsType", + "NameResolutionError", + "NamespacePackage", + "NumpyOptions", + "Object", + "ObjectAliasMixin", + "ObjectChangedKindBreakage", + "ObjectKind", + "ObjectNode", + "ObjectRemovedBreakage", + "Package", + "Parameter", + "ParameterAddedRequiredBreakage", + "ParameterChangedDefaultBreakage", + "ParameterChangedKindBreakage", + "ParameterChangedRequiredBreakage", + "ParameterKind", + "ParameterMovedBreakage", + "ParameterRemovedBreakage", + "Parameters", + "ParametersType", + "Parser", + "PerStyleOptions", + "ReturnChangedTypeBreakage", + "RootNodeError", + "SerializationMixin", + "SetMembersMixin", + "SphinxOptions", + "Stats", + "TmpPackage", + "TypeAlias", + "TypeParameter", + "TypeParameterKind", + "TypeParameters", + "UnhandledEditableModuleError", + "UnimportableModuleError", + "UnpackTypedDictExtension", + "Visitor", + "assert_git_repo", + "ast_children", + "ast_first_child", + "ast_kind", + "ast_last_child", + "ast_next", + "ast_next_siblings", + "ast_previous", + "ast_previous_siblings", + "ast_siblings", + "builtin_decorators", + "builtin_extensions", + "c3linear_merge", + "check", + "docstring_warning", + "dump", + "dynamic_import", + "find_breaking_changes", + "get__all__", + "get_annotation", + "get_base_class", + "get_class_keyword", + "get_condition", + "get_docstring", + "get_expression", + "get_instance_names", + "get_latest_tag", + "get_logger", + "get_name", + "get_names", + "get_parameters", + "get_parser", + "get_repo_root", + "get_value", + "htree", + "infer_docstring_style", + "inspect", + "json_decoder", + "load", + "load_extensions", + "load_git", + "load_pypi", + "logger", + "main", + "merge_stubs", + "module_vtree", + "parse", + "parse_auto", + "parse_docstring_annotation", + "parse_google", + "parse_numpy", + "parse_sphinx", + "parsers", + "patch_loggers", + "relative_to_absolute", + "safe_get__all__", + "safe_get_annotation", + "safe_get_base_class", + "safe_get_class_keyword", + "safe_get_condition", + "safe_get_expression", + "safe_get_value", + "stdlib_decorators", + "sys_path", + "temporary_inspected_module", + "temporary_inspected_package", + "temporary_pyfile", + "temporary_pypackage", + "temporary_visited_module", + "temporary_visited_package", + "tmp_worktree", + "typing_overload", + "visit", + "vtree", +] diff --git a/src/griffe/_internal/__init__.py b/packages/griffelib/src/griffelib/_internal/__init__.py similarity index 100% rename from src/griffe/_internal/__init__.py rename to packages/griffelib/src/griffelib/_internal/__init__.py diff --git a/src/griffe/_internal/agents/__init__.py b/packages/griffelib/src/griffelib/_internal/agents/__init__.py similarity index 100% rename from src/griffe/_internal/agents/__init__.py rename to packages/griffelib/src/griffelib/_internal/agents/__init__.py diff --git a/src/griffe/_internal/agents/inspector.py b/packages/griffelib/src/griffelib/_internal/agents/inspector.py similarity index 97% rename from src/griffe/_internal/agents/inspector.py rename to packages/griffelib/src/griffelib/_internal/agents/inspector.py index 1ff89bfe6..896b5a5e2 100644 --- a/src/griffe/_internal/agents/inspector.py +++ b/packages/griffelib/src/griffelib/_internal/agents/inspector.py @@ -12,14 +12,14 @@ from inspect import signature as getsignature from typing import TYPE_CHECKING, Any -from griffe._internal.agents.nodes.runtime import ObjectNode -from griffe._internal.collections import LinesCollection, ModulesCollection -from griffe._internal.enumerations import Kind, ParameterKind, TypeParameterKind -from griffe._internal.expressions import Expr, ExprBinOp, ExprSubscript, ExprTuple, safe_get_annotation -from griffe._internal.extensions.base import Extensions, load_extensions -from griffe._internal.importer import dynamic_import -from griffe._internal.logger import logger -from griffe._internal.models import ( +from griffelib._internal.agents.nodes.runtime import ObjectNode +from griffelib._internal.collections import LinesCollection, ModulesCollection +from griffelib._internal.enumerations import Kind, ParameterKind, TypeParameterKind +from griffelib._internal.expressions import Expr, ExprBinOp, ExprSubscript, ExprTuple, safe_get_annotation +from griffelib._internal.extensions.base import Extensions, load_extensions +from griffelib._internal.importer import dynamic_import +from griffelib._internal.logger import logger +from griffelib._internal.models import ( Alias, Attribute, Class, @@ -37,8 +37,8 @@ from collections.abc import Sequence from pathlib import Path - from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle - from griffe._internal.enumerations import Parser + from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle + from griffelib._internal.enumerations import Parser _TYPING_MODULES: tuple[types.ModuleType, ...] try: diff --git a/src/griffe/_internal/agents/nodes/__init__.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/__init__.py similarity index 100% rename from src/griffe/_internal/agents/nodes/__init__.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/__init__.py diff --git a/src/griffe/_internal/agents/nodes/assignments.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/assignments.py similarity index 100% rename from src/griffe/_internal/agents/nodes/assignments.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/assignments.py diff --git a/src/griffe/_internal/agents/nodes/ast.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/ast.py similarity index 98% rename from src/griffe/_internal/agents/nodes/ast.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/ast.py index 9cb261486..778fd75ef 100644 --- a/src/griffe/_internal/agents/nodes/ast.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/ast.py @@ -5,7 +5,7 @@ from ast import AST from typing import TYPE_CHECKING -from griffe._internal.exceptions import LastNodeError +from griffelib._internal.exceptions import LastNodeError if TYPE_CHECKING: from collections.abc import Iterator diff --git a/src/griffe/_internal/agents/nodes/docstrings.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/docstrings.py similarity index 100% rename from src/griffe/_internal/agents/nodes/docstrings.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/docstrings.py diff --git a/src/griffe/_internal/agents/nodes/exports.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py similarity index 92% rename from src/griffe/_internal/agents/nodes/exports.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py index f2e9caff3..8001ad5f8 100644 --- a/src/griffe/_internal/agents/nodes/exports.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py @@ -7,13 +7,13 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable -from griffe._internal.agents.nodes.values import get_value -from griffe._internal.enumerations import LogLevel -from griffe._internal.expressions import ExprName -from griffe._internal.logger import logger +from griffelib._internal.agents.nodes.values import get_value +from griffelib._internal.enumerations import LogLevel +from griffelib._internal.expressions import ExprName +from griffelib._internal.logger import logger if TYPE_CHECKING: - from griffe._internal.models import Module + from griffelib._internal.models import Module # YORE: Bump 2: Remove block. diff --git a/src/griffe/_internal/agents/nodes/imports.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/imports.py similarity index 95% rename from src/griffe/_internal/agents/nodes/imports.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/imports.py index c194d07bc..25b5cf1b6 100644 --- a/src/griffe/_internal/agents/nodes/imports.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/imports.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import ast - from griffe._internal.models import Module + from griffelib._internal.models import Module def relative_to_absolute(node: ast.ImportFrom, name: ast.alias, current_module: Module) -> str: diff --git a/src/griffe/_internal/agents/nodes/parameters.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/parameters.py similarity index 97% rename from src/griffe/_internal/agents/nodes/parameters.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/parameters.py index b6b6f445d..349be63d1 100644 --- a/src/griffe/_internal/agents/nodes/parameters.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/parameters.py @@ -6,7 +6,7 @@ from itertools import zip_longest from typing import TYPE_CHECKING, Optional, Union -from griffe._internal.enumerations import ParameterKind +from griffelib._internal.enumerations import ParameterKind if TYPE_CHECKING: from collections.abc import Iterable diff --git a/src/griffe/_internal/agents/nodes/runtime.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/runtime.py similarity index 99% rename from src/griffe/_internal/agents/nodes/runtime.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/runtime.py index b63d4f9c9..693a82a8f 100644 --- a/src/griffe/_internal/agents/nodes/runtime.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/runtime.py @@ -9,8 +9,8 @@ from types import GetSetDescriptorType, ModuleType from typing import TYPE_CHECKING, Any, ClassVar -from griffe._internal.enumerations import ObjectKind -from griffe._internal.logger import logger +from griffelib._internal.enumerations import ObjectKind +from griffelib._internal.logger import logger if TYPE_CHECKING: import types diff --git a/src/griffe/_internal/agents/nodes/values.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/values.py similarity index 96% rename from src/griffe/_internal/agents/nodes/values.py rename to packages/griffelib/src/griffelib/_internal/agents/nodes/values.py index 63941f823..89465b97d 100644 --- a/src/griffe/_internal/agents/nodes/values.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/values.py @@ -6,7 +6,7 @@ from ast import unparse from typing import TYPE_CHECKING -from griffe._internal.logger import logger +from griffelib._internal.logger import logger if TYPE_CHECKING: from pathlib import Path diff --git a/src/griffe/_internal/agents/visitor.py b/packages/griffelib/src/griffelib/_internal/agents/visitor.py similarity index 96% rename from src/griffe/_internal/agents/visitor.py rename to packages/griffelib/src/griffelib/_internal/agents/visitor.py index 7cad06dde..b6b2e537c 100644 --- a/src/griffe/_internal/agents/visitor.py +++ b/packages/griffelib/src/griffelib/_internal/agents/visitor.py @@ -8,20 +8,20 @@ from contextlib import suppress from typing import TYPE_CHECKING, Final -from griffe._internal.agents.nodes.assignments import get_instance_names, get_names -from griffe._internal.agents.nodes.ast import ( +from griffelib._internal.agents.nodes.assignments import get_instance_names, get_names +from griffelib._internal.agents.nodes.ast import ( ast_children, ast_kind, ast_next, ) -from griffe._internal.agents.nodes.docstrings import get_docstring -from griffe._internal.agents.nodes.exports import safe_get__all__ -from griffe._internal.agents.nodes.imports import relative_to_absolute -from griffe._internal.agents.nodes.parameters import get_parameters -from griffe._internal.collections import LinesCollection, ModulesCollection -from griffe._internal.enumerations import Kind, TypeParameterKind -from griffe._internal.exceptions import AliasResolutionError, CyclicAliasError, LastNodeError -from griffe._internal.expressions import ( +from griffelib._internal.agents.nodes.docstrings import get_docstring +from griffelib._internal.agents.nodes.exports import safe_get__all__ +from griffelib._internal.agents.nodes.imports import relative_to_absolute +from griffelib._internal.agents.nodes.parameters import get_parameters +from griffelib._internal.collections import LinesCollection, ModulesCollection +from griffelib._internal.enumerations import Kind, TypeParameterKind +from griffelib._internal.exceptions import AliasResolutionError, CyclicAliasError, LastNodeError +from griffelib._internal.expressions import ( Expr, ExprName, safe_get_annotation, @@ -30,8 +30,8 @@ safe_get_condition, safe_get_expression, ) -from griffe._internal.extensions.base import Extensions, load_extensions -from griffe._internal.models import ( +from griffelib._internal.extensions.base import Extensions, load_extensions +from griffelib._internal.models import ( Alias, Attribute, Class, @@ -49,8 +49,8 @@ if TYPE_CHECKING: from pathlib import Path - from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle - from griffe._internal.enumerations import Parser + from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle + from griffelib._internal.enumerations import Parser builtin_decorators = { diff --git a/src/griffe/_internal/c3linear.py b/packages/griffelib/src/griffelib/_internal/c3linear.py similarity index 100% rename from src/griffe/_internal/c3linear.py rename to packages/griffelib/src/griffelib/_internal/c3linear.py diff --git a/src/griffe/_internal/collections.py b/packages/griffelib/src/griffelib/_internal/collections.py similarity index 94% rename from src/griffe/_internal/collections.py rename to packages/griffelib/src/griffelib/_internal/collections.py index 787f57a73..9927855a2 100644 --- a/src/griffe/_internal/collections.py +++ b/packages/griffelib/src/griffelib/_internal/collections.py @@ -5,13 +5,13 @@ from typing import TYPE_CHECKING, Any -from griffe._internal.mixins import DelMembersMixin, GetMembersMixin, SetMembersMixin +from griffelib._internal.mixins import DelMembersMixin, GetMembersMixin, SetMembersMixin if TYPE_CHECKING: from collections.abc import ItemsView, KeysView, ValuesView from pathlib import Path - from griffe._internal.models import Module + from griffelib._internal.models import Module class LinesCollection: diff --git a/src/griffe/_internal/debug.py b/packages/griffelib/src/griffelib/_internal/debug.py similarity index 100% rename from src/griffe/_internal/debug.py rename to packages/griffelib/src/griffelib/_internal/debug.py diff --git a/src/griffe/_internal/diff.py b/packages/griffelib/src/griffelib/_internal/diff.py similarity index 97% rename from src/griffe/_internal/diff.py rename to packages/griffelib/src/griffelib/_internal/diff.py index 59e98f08f..2c6589515 100644 --- a/src/griffe/_internal/diff.py +++ b/packages/griffelib/src/griffelib/_internal/diff.py @@ -12,15 +12,15 @@ from pathlib import Path from typing import TYPE_CHECKING, Any -from griffe._internal.enumerations import BreakageKind, ExplanationStyle, ParameterKind -from griffe._internal.exceptions import AliasResolutionError -from griffe._internal.git import _WORKTREE_PREFIX -from griffe._internal.logger import logger +from griffelib._internal.enumerations import BreakageKind, ExplanationStyle, ParameterKind +from griffelib._internal.exceptions import AliasResolutionError +from griffelib._internal.git import _WORKTREE_PREFIX +from griffelib._internal.logger import logger if TYPE_CHECKING: from collections.abc import Iterable, Iterator - from griffe._internal.models import Alias, Attribute, Class, Function, Object + from griffelib._internal.models import Alias, Attribute, Class, Function, Object _POSITIONAL = frozenset((ParameterKind.positional_only, ParameterKind.positional_or_keyword)) _KEYWORD = frozenset((ParameterKind.keyword_only, ParameterKind.positional_or_keyword)) @@ -674,10 +674,10 @@ def find_breaking_changes( Breaking changes. Examples: - >>> import sys, griffe - >>> new = griffe.load("pkg") - >>> old = griffe.load_git("pkg", "1.2.3") - >>> for breakage in griffe.find_breaking_changes(old, new) + >>> import sys, griffelib + >>> new = griffelib.load("pkg") + >>> old = griffelib.load_git("pkg", "1.2.3") + >>> for breakage in griffelib.find_breaking_changes(old, new) ... print(breakage.explain(style=style), file=sys.stderr) """ yield from _member_incompatibilities(old_obj, new_obj) diff --git a/src/griffe/_internal/docstrings/__init__.py b/packages/griffelib/src/griffelib/_internal/docstrings/__init__.py similarity index 100% rename from src/griffe/_internal/docstrings/__init__.py rename to packages/griffelib/src/griffelib/_internal/docstrings/__init__.py diff --git a/src/griffe/_internal/docstrings/auto.py b/packages/griffelib/src/griffelib/_internal/docstrings/auto.py similarity index 93% rename from src/griffe/_internal/docstrings/auto.py rename to packages/griffelib/src/griffelib/_internal/docstrings/auto.py index ecd3a1d66..0bc888021 100644 --- a/src/griffe/_internal/docstrings/auto.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/auto.py @@ -6,15 +6,15 @@ from typing import TYPE_CHECKING, Any, Literal, TypedDict from warnings import warn -from griffe._internal.enumerations import Parser +from griffelib._internal.enumerations import Parser if TYPE_CHECKING: - from griffe._internal.docstrings.google import GoogleOptions - from griffe._internal.docstrings.models import DocstringSection - from griffe._internal.docstrings.numpy import NumpyOptions - from griffe._internal.docstrings.parsers import DocstringStyle - from griffe._internal.docstrings.sphinx import SphinxOptions - from griffe._internal.models import Docstring + from griffelib._internal.docstrings.google import GoogleOptions + from griffelib._internal.docstrings.models import DocstringSection + from griffelib._internal.docstrings.numpy import NumpyOptions + from griffelib._internal.docstrings.parsers import DocstringStyle + from griffelib._internal.docstrings.sphinx import SphinxOptions + from griffelib._internal.models import Docstring # This is not our preferred order, but the safest order for proper detection @@ -147,7 +147,7 @@ def infer_docstring_style( Returns: The inferred parser, and optionally parsed sections (when method is 'max_sections'). """ - from griffe._internal.docstrings.parsers import parsers # noqa: PLC0415 + from griffelib._internal.docstrings.parsers import parsers # noqa: PLC0415 # YORE: Bump 2: Replace block with `per_style_options = per_style_options or {}`. if options: @@ -222,7 +222,7 @@ def parse_auto( Returns: A list of docstring sections. """ - from griffe._internal.docstrings.parsers import parse # noqa: PLC0415 + from griffelib._internal.docstrings.parsers import parse # noqa: PLC0415 # YORE: Bump 2: Replace block with `per_style_options = per_style_options or {}`. if options: diff --git a/src/griffe/_internal/docstrings/google.py b/packages/griffelib/src/griffelib/_internal/docstrings/google.py similarity index 99% rename from src/griffe/_internal/docstrings/google.py rename to packages/griffelib/src/griffelib/_internal/docstrings/google.py index 5b9b542af..27b585964 100644 --- a/src/griffe/_internal/docstrings/google.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/google.py @@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, TypedDict from warnings import warn -from griffe._internal.docstrings.models import ( +from griffelib._internal.docstrings.models import ( DocstringAttribute, DocstringClass, DocstringFunction, @@ -38,15 +38,15 @@ DocstringWarn, DocstringYield, ) -from griffe._internal.docstrings.utils import docstring_warning, parse_docstring_annotation -from griffe._internal.enumerations import DocstringSectionKind, LogLevel +from griffelib._internal.docstrings.utils import docstring_warning, parse_docstring_annotation +from griffelib._internal.enumerations import DocstringSectionKind, LogLevel if TYPE_CHECKING: from re import Pattern from typing import Any, Literal - from griffe._internal.expressions import Expr - from griffe._internal.models import Docstring + from griffelib._internal.expressions import Expr + from griffelib._internal.models import Docstring _section_kind = { diff --git a/src/griffe/_internal/docstrings/models.py b/packages/griffelib/src/griffelib/_internal/docstrings/models.py similarity index 98% rename from src/griffe/_internal/docstrings/models.py rename to packages/griffelib/src/griffelib/_internal/docstrings/models.py index 545ea78d1..ce444eb80 100644 --- a/src/griffe/_internal/docstrings/models.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/models.py @@ -4,14 +4,14 @@ from typing import TYPE_CHECKING -from griffe._internal.enumerations import DocstringSectionKind -from griffe._internal.expressions import ExprTuple +from griffelib._internal.enumerations import DocstringSectionKind +from griffelib._internal.expressions import ExprTuple if TYPE_CHECKING: from collections.abc import Sequence from typing import Any, Literal - from griffe._internal.expressions import Expr + from griffelib._internal.expressions import Expr # Elements ----------------------------------------------- diff --git a/src/griffe/_internal/docstrings/numpy.py b/packages/griffelib/src/griffelib/_internal/docstrings/numpy.py similarity index 98% rename from src/griffe/_internal/docstrings/numpy.py rename to packages/griffelib/src/griffelib/_internal/docstrings/numpy.py index 1291f1723..6dcf29de5 100644 --- a/src/griffe/_internal/docstrings/numpy.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/numpy.py @@ -25,7 +25,7 @@ from typing import TYPE_CHECKING, TypedDict from warnings import warn -from griffe._internal.docstrings.models import ( +from griffelib._internal.docstrings.models import ( DocstringAttribute, DocstringClass, DocstringFunction, @@ -57,16 +57,16 @@ DocstringWarn, DocstringYield, ) -from griffe._internal.docstrings.utils import docstring_warning, parse_docstring_annotation -from griffe._internal.enumerations import DocstringSectionKind, LogLevel -from griffe._internal.expressions import ExprName +from griffelib._internal.docstrings.utils import docstring_warning, parse_docstring_annotation +from griffelib._internal.enumerations import DocstringSectionKind, LogLevel +from griffelib._internal.expressions import ExprName if TYPE_CHECKING: from re import Pattern from typing import Any, Literal - from griffe._internal.expressions import Expr - from griffe._internal.models import Docstring + from griffelib._internal.expressions import Expr + from griffelib._internal.models import Docstring _section_kind = { diff --git a/src/griffe/_internal/docstrings/parsers.py b/packages/griffelib/src/griffelib/_internal/docstrings/parsers.py similarity index 72% rename from src/griffe/_internal/docstrings/parsers.py rename to packages/griffelib/src/griffelib/_internal/docstrings/parsers.py index bb91f600a..f24ff1f7d 100644 --- a/src/griffe/_internal/docstrings/parsers.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/parsers.py @@ -5,15 +5,15 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, Union -from griffe._internal.docstrings.auto import AutoOptions, parse_auto -from griffe._internal.docstrings.google import GoogleOptions, parse_google -from griffe._internal.docstrings.models import DocstringSection, DocstringSectionText -from griffe._internal.docstrings.numpy import NumpyOptions, parse_numpy -from griffe._internal.docstrings.sphinx import SphinxOptions, parse_sphinx -from griffe._internal.enumerations import Parser +from griffelib._internal.docstrings.auto import AutoOptions, parse_auto +from griffelib._internal.docstrings.google import GoogleOptions, parse_google +from griffelib._internal.docstrings.models import DocstringSection, DocstringSectionText +from griffelib._internal.docstrings.numpy import NumpyOptions, parse_numpy +from griffelib._internal.docstrings.sphinx import SphinxOptions, parse_sphinx +from griffelib._internal.enumerations import Parser if TYPE_CHECKING: - from griffe._internal.models import Docstring + from griffelib._internal.models import Docstring DocstringStyle = Literal["google", "numpy", "sphinx", "auto"] diff --git a/src/griffe/_internal/docstrings/sphinx.py b/packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py similarity index 98% rename from src/griffe/_internal/docstrings/sphinx.py rename to packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py index 7059169bc..2a24d8f1b 100644 --- a/src/griffe/_internal/docstrings/sphinx.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any, Callable, TypedDict from warnings import warn -from griffe._internal.docstrings.models import ( +from griffelib._internal.docstrings.models import ( DocstringAttribute, DocstringParameter, DocstringRaise, @@ -23,11 +23,11 @@ DocstringSectionReturns, DocstringSectionText, ) -from griffe._internal.docstrings.utils import docstring_warning, parse_docstring_annotation +from griffelib._internal.docstrings.utils import docstring_warning, parse_docstring_annotation if TYPE_CHECKING: - from griffe._internal.expressions import Expr - from griffe._internal.models import Docstring + from griffelib._internal.expressions import Expr + from griffelib._internal.models import Docstring # TODO: Examples: from the documentation, we're not sure there is a standard format for examples diff --git a/src/griffe/_internal/docstrings/utils.py b/packages/griffelib/src/griffelib/_internal/docstrings/utils.py similarity index 88% rename from src/griffe/_internal/docstrings/utils.py rename to packages/griffelib/src/griffelib/_internal/docstrings/utils.py index 4c67069b0..5d2423cf7 100644 --- a/src/griffe/_internal/docstrings/utils.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/utils.py @@ -6,14 +6,14 @@ from contextlib import suppress from typing import TYPE_CHECKING -from griffe._internal.enumerations import LogLevel -from griffe._internal.exceptions import BuiltinModuleError -from griffe._internal.expressions import safe_get_annotation -from griffe._internal.logger import logger +from griffelib._internal.enumerations import LogLevel +from griffelib._internal.exceptions import BuiltinModuleError +from griffelib._internal.expressions import safe_get_annotation +from griffelib._internal.logger import logger if TYPE_CHECKING: - from griffe._internal.expressions import Expr - from griffe._internal.models import Docstring + from griffelib._internal.expressions import Expr + from griffelib._internal.models import Docstring def docstring_warning( diff --git a/src/griffe/_internal/encoders.py b/packages/griffelib/src/griffelib/_internal/encoders.py similarity index 97% rename from src/griffe/_internal/encoders.py rename to packages/griffelib/src/griffelib/_internal/encoders.py index d485e2a17..356233dfb 100644 --- a/src/griffe/_internal/encoders.py +++ b/packages/griffelib/src/griffelib/_internal/encoders.py @@ -7,10 +7,10 @@ from pathlib import Path, PosixPath, WindowsPath from typing import Any, Callable -from griffe._internal import expressions -from griffe._internal.enumerations import Kind, ParameterKind, TypeParameterKind -from griffe._internal.git import GitInfo -from griffe._internal.models import ( +from griffelib._internal import expressions +from griffelib._internal.enumerations import Kind, ParameterKind, TypeParameterKind +from griffelib._internal.git import GitInfo +from griffelib._internal.models import ( Alias, Attribute, Class, @@ -41,11 +41,11 @@ class JSONEncoder(json.JSONEncoder): the [`json.dump`][] or [`json.dumps`][] methods. Examples: - >>> from griffe import JSONEncoder + >>> from griffelib import JSONEncoder >>> JSONEncoder(full=True).encode(..., **kwargs) >>> import json - >>> from griffe import JSONEncoder + >>> from griffelib import JSONEncoder >>> json.dumps(..., cls=JSONEncoder, full=True, **kwargs) """ @@ -350,7 +350,7 @@ def json_decoder( Examples: >>> import json - >>> from griffe import json_decoder + >>> from griffelib import json_decoder >>> json.loads(..., object_hook=json_decoder) Parameters: diff --git a/src/griffe/_internal/enumerations.py b/packages/griffelib/src/griffelib/_internal/enumerations.py similarity index 100% rename from src/griffe/_internal/enumerations.py rename to packages/griffelib/src/griffelib/_internal/enumerations.py diff --git a/src/griffe/_internal/exceptions.py b/packages/griffelib/src/griffelib/_internal/exceptions.py similarity index 98% rename from src/griffe/_internal/exceptions.py rename to packages/griffelib/src/griffelib/_internal/exceptions.py index 4d104aa8e..3b864f7ad 100644 --- a/src/griffe/_internal/exceptions.py +++ b/packages/griffelib/src/griffelib/_internal/exceptions.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from griffe._internal.models import Alias + from griffelib._internal.models import Alias class GriffeError(Exception): diff --git a/src/griffe/_internal/expressions.py b/packages/griffelib/src/griffelib/_internal/expressions.py similarity index 99% rename from src/griffe/_internal/expressions.py rename to packages/griffelib/src/griffelib/_internal/expressions.py index 702bc56aa..2d2ebf7dd 100644 --- a/src/griffe/_internal/expressions.py +++ b/packages/griffelib/src/griffelib/_internal/expressions.py @@ -13,16 +13,16 @@ from functools import partial from typing import TYPE_CHECKING, Any, Protocol -from griffe._internal.agents.nodes.parameters import get_parameters -from griffe._internal.enumerations import LogLevel, ParameterKind -from griffe._internal.exceptions import NameResolutionError -from griffe._internal.logger import logger +from griffelib._internal.agents.nodes.parameters import get_parameters +from griffelib._internal.enumerations import LogLevel, ParameterKind +from griffelib._internal.exceptions import NameResolutionError +from griffelib._internal.logger import logger if TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence from pathlib import Path - from griffe._internal.models import Class, Function, Module + from griffelib._internal.models import Class, Function, Module class _OperatorPrecedence(IntEnum): diff --git a/src/griffe/_internal/extensions/__init__.py b/packages/griffelib/src/griffelib/_internal/extensions/__init__.py similarity index 100% rename from src/griffe/_internal/extensions/__init__.py rename to packages/griffelib/src/griffelib/_internal/extensions/__init__.py diff --git a/src/griffe/_internal/extensions/base.py b/packages/griffelib/src/griffelib/_internal/extensions/base.py similarity index 97% rename from src/griffe/_internal/extensions/base.py rename to packages/griffelib/src/griffelib/_internal/extensions/base.py index 8f67da61e..e5ff82b09 100644 --- a/src/griffe/_internal/extensions/base.py +++ b/packages/griffelib/src/griffelib/_internal/extensions/base.py @@ -13,19 +13,19 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Union -from griffe._internal.agents.nodes.ast import ast_children, ast_kind -from griffe._internal.exceptions import ExtensionNotLoadedError -from griffe._internal.importer import dynamic_import +from griffelib._internal.agents.nodes.ast import ast_children, ast_kind +from griffelib._internal.exceptions import ExtensionNotLoadedError +from griffelib._internal.importer import dynamic_import if TYPE_CHECKING: import ast from types import ModuleType - from griffe._internal.agents.inspector import Inspector - from griffe._internal.agents.nodes.runtime import ObjectNode - from griffe._internal.agents.visitor import Visitor - from griffe._internal.loader import GriffeLoader - from griffe._internal.models import Alias, Attribute, Class, Function, Module, Object, TypeAlias + from griffelib._internal.agents.inspector import Inspector + from griffelib._internal.agents.nodes.runtime import ObjectNode + from griffelib._internal.agents.visitor import Visitor + from griffelib._internal.loader import GriffeLoader + from griffelib._internal.models import Alias, Attribute, Class, Function, Module, Object, TypeAlias # YORE: Bump 2: Remove block. @@ -647,7 +647,7 @@ def load_extensions(*exts: LoadableExtensionType) -> Extensions: # TODO: Deprecate and remove at some point? # Always add our built-in dataclasses extension. - from griffe._internal.extensions.dataclasses import DataclassesExtension # noqa: PLC0415 + from griffelib._internal.extensions.dataclasses import DataclassesExtension # noqa: PLC0415 for ext in extensions._extensions: if type(ext) is DataclassesExtension: diff --git a/src/griffe/_internal/extensions/dataclasses.py b/packages/griffelib/src/griffelib/_internal/extensions/dataclasses.py similarity index 96% rename from src/griffe/_internal/extensions/dataclasses.py rename to packages/griffelib/src/griffelib/_internal/extensions/dataclasses.py index 5e6fa7b01..100b858ad 100644 --- a/src/griffe/_internal/extensions/dataclasses.py +++ b/packages/griffelib/src/griffelib/_internal/extensions/dataclasses.py @@ -10,16 +10,16 @@ from functools import cache from typing import Any, cast -from griffe._internal.enumerations import ParameterKind -from griffe._internal.expressions import ( +from griffelib._internal.enumerations import ParameterKind +from griffelib._internal.expressions import ( Expr, ExprAttribute, ExprCall, ExprDict, ) -from griffe._internal.extensions.base import Extension -from griffe._internal.logger import logger -from griffe._internal.models import Attribute, Class, Decorator, Function, Module, Parameter, Parameters +from griffelib._internal.extensions.base import Extension +from griffelib._internal.logger import logger +from griffelib._internal.models import Attribute, Class, Decorator, Function, Module, Parameter, Parameters def _dataclass_decorator(decorators: list[Decorator]) -> Expr | None: diff --git a/src/griffe/_internal/extensions/unpack_typeddict.py b/packages/griffelib/src/griffelib/_internal/extensions/unpack_typeddict.py similarity index 96% rename from src/griffe/_internal/extensions/unpack_typeddict.py rename to packages/griffelib/src/griffelib/_internal/extensions/unpack_typeddict.py index 162cbbf69..d228c9d3c 100644 --- a/src/griffe/_internal/extensions/unpack_typeddict.py +++ b/packages/griffelib/src/griffelib/_internal/extensions/unpack_typeddict.py @@ -7,14 +7,14 @@ from itertools import chain from typing import TYPE_CHECKING, Any, TypedDict -from griffe._internal.docstrings.models import ( +from griffelib._internal.docstrings.models import ( DocstringParameter, DocstringSectionParameters, ) -from griffe._internal.enumerations import DocstringSectionKind, ParameterKind -from griffe._internal.expressions import Expr, ExprSubscript -from griffe._internal.extensions.base import Extension -from griffe._internal.models import Class, Docstring, Function, Parameter, Parameters +from griffelib._internal.enumerations import DocstringSectionKind, ParameterKind +from griffelib._internal.expressions import Expr, ExprSubscript +from griffelib._internal.extensions.base import Extension +from griffelib._internal.models import Class, Docstring, Function, Parameter, Parameters if TYPE_CHECKING: from collections.abc import Iterable, Iterator diff --git a/src/griffe/_internal/finder.py b/packages/griffelib/src/griffelib/_internal/finder.py similarity index 97% rename from src/griffe/_internal/finder.py rename to packages/griffelib/src/griffelib/_internal/finder.py index 23bc3be29..198d15fa6 100644 --- a/src/griffe/_internal/finder.py +++ b/packages/griffelib/src/griffelib/_internal/finder.py @@ -9,8 +9,8 @@ # ModuleSpec( # name='griffe.agents', # loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa5f34e8110>, -# origin='/media/data/dev/griffe/src/griffe/agents/__init__.py', -# submodule_search_locations=['/media/data/dev/griffe/src/griffe/agents'], +# origin='/media/data/dev/griffe/packages/griffe/src/griffe/agents/__init__.py', +# submodule_search_locations=['/media/data/dev/griffe/packages/griffe/src/griffe/agents'], # ) # ``` @@ -27,14 +27,14 @@ from pathlib import Path from typing import TYPE_CHECKING, ClassVar -from griffe._internal.exceptions import UnhandledEditableModuleError -from griffe._internal.logger import logger +from griffelib._internal.exceptions import UnhandledEditableModuleError +from griffelib._internal.logger import logger if TYPE_CHECKING: from collections.abc import Iterator, Sequence from re import Pattern - from griffe._internal.models import Module + from griffelib._internal.models import Module _editable_editables_patterns = [re.compile(pat) for pat in (r"^__editables_\w+\.py$", r"^_editable_impl_\w+\.py$")] @@ -470,9 +470,9 @@ def _handle_pth_file(path: Path) -> list[_SP]: def _handle_editable_module(path: Path) -> list[_SP]: if _match_pattern(path.name, (*_editable_editables_patterns, *_editable_scikit_build_core_patterns)): # Support for how 'editables' write these files: - # example line: `F.map_module('griffe', '/media/data/dev/griffe/src/griffe/__init__.py')`. + # example line: `F.map_module('griffe', '/media/data/dev/griffe/packages/griffe/src/griffe/__init__.py')`. # And how 'scikit-build-core' writes these files: - # example line: `install({'griffe': '/media/data/dev/griffe/src/griffe/__init__.py'}, {'cmake_example': ...}, None, False, True)`. + # example line: `install({'griffe': '/media/data/dev/griffe/packages/griffe/src/griffe/__init__.py'}, {'cmake_example': ...}, None, False, True)`. try: editable_lines = path.read_text(encoding="utf-8-sig").strip().splitlines(keepends=False) except FileNotFoundError as error: @@ -483,7 +483,7 @@ def _handle_editable_module(path: Path) -> list[_SP]: return [_SP(new_path)] if _match_pattern(path.name, _editable_setuptools_patterns): # Support for how 'setuptools' writes these files: - # example line: `MAPPING = {'griffe': '/media/data/dev/griffe/src/griffe', 'briffe': '/media/data/dev/griffe/src/briffe'}`. + # example line: `MAPPING = {'griffe': '/media/data/dev/griffe/packages/griffe/src/griffe', 'briffe': '/media/data/dev/griffe/src/briffe'}`. # with annotation: `MAPPING: dict[str, str] = {...}`. parsed_module = ast.parse(path.read_text(encoding="utf8")) for node in parsed_module.body: diff --git a/src/griffe/_internal/git.py b/packages/griffelib/src/griffelib/_internal/git.py similarity index 98% rename from src/griffe/_internal/git.py rename to packages/griffelib/src/griffelib/_internal/git.py index 47642c009..d3ab094db 100644 --- a/src/griffe/_internal/git.py +++ b/packages/griffelib/src/griffelib/_internal/git.py @@ -16,12 +16,12 @@ from typing import TYPE_CHECKING, Literal from urllib.parse import urlsplit, urlunsplit -from griffe._internal.exceptions import BuiltinModuleError, GitError +from griffelib._internal.exceptions import BuiltinModuleError, GitError if TYPE_CHECKING: from collections.abc import Iterator - from griffe._internal.models import Module + from griffelib._internal.models import Module _WORKTREE_PREFIX = "griffe-worktree-" diff --git a/src/griffe/_internal/importer.py b/packages/griffelib/src/griffelib/_internal/importer.py similarity index 100% rename from src/griffe/_internal/importer.py rename to packages/griffelib/src/griffelib/_internal/importer.py diff --git a/src/griffe/_internal/loader.py b/packages/griffelib/src/griffelib/_internal/loader.py similarity index 97% rename from src/griffe/_internal/loader.py rename to packages/griffelib/src/griffelib/_internal/loader.py index cfe2be80c..e25245a6a 100644 --- a/src/griffe/_internal/loader.py +++ b/packages/griffelib/src/griffelib/_internal/loader.py @@ -14,31 +14,31 @@ from pathlib import Path from typing import TYPE_CHECKING, ClassVar, cast -from griffe._internal.agents.inspector import inspect -from griffe._internal.agents.visitor import visit -from griffe._internal.collections import LinesCollection, ModulesCollection -from griffe._internal.enumerations import Kind -from griffe._internal.exceptions import ( +from griffelib._internal.agents.inspector import inspect +from griffelib._internal.agents.visitor import visit +from griffelib._internal.collections import LinesCollection, ModulesCollection +from griffelib._internal.enumerations import Kind +from griffelib._internal.exceptions import ( AliasResolutionError, CyclicAliasError, LoadingError, UnimportableModuleError, ) -from griffe._internal.expressions import ExprName -from griffe._internal.extensions.base import Extensions, load_extensions -from griffe._internal.finder import ModuleFinder, NamespacePackage, Package -from griffe._internal.git import GitInfo, _tmp_worktree -from griffe._internal.importer import dynamic_import -from griffe._internal.logger import logger -from griffe._internal.merger import merge_stubs -from griffe._internal.models import Alias, Module, Object -from griffe._internal.stats import Stats +from griffelib._internal.expressions import ExprName +from griffelib._internal.extensions.base import Extensions, load_extensions +from griffelib._internal.finder import ModuleFinder, NamespacePackage, Package +from griffelib._internal.git import GitInfo, _tmp_worktree +from griffelib._internal.importer import dynamic_import +from griffelib._internal.logger import logger +from griffelib._internal.merger import merge_stubs +from griffelib._internal.models import Alias, Module, Object +from griffelib._internal.stats import Stats if TYPE_CHECKING: from collections.abc import Sequence - from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle - from griffe._internal.enumerations import Parser + from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle + from griffelib._internal.enumerations import Parser class GriffeLoader: @@ -787,15 +787,15 @@ def load( Example: ```python - import griffe + import griffelib - module = griffe.load(...) + module = griffelib.load(...) ``` This is a shortcut for: ```python - from griffe import GriffeLoader + from griffelib import GriffeLoader loader = GriffeLoader(...) module = loader.load(...) @@ -881,7 +881,7 @@ def load_git( Examples: ```python - from griffe import load_git + from griffelib import load_git old_api = load_git("my_module", ref="v0.1.0", repo="path/to/repo") ``` diff --git a/src/griffe/_internal/logger.py b/packages/griffelib/src/griffelib/_internal/logger.py similarity index 98% rename from src/griffe/_internal/logger.py rename to packages/griffelib/src/griffelib/_internal/logger.py index 6a7290fc3..c6679104f 100644 --- a/src/griffe/_internal/logger.py +++ b/packages/griffelib/src/griffelib/_internal/logger.py @@ -68,7 +68,7 @@ def _patch_loggers(cls, get_logger_func: Callable) -> None: ```python import logging -from griffe import patch_loggers +from griffelib import patch_loggers class LoggerAdapter(logging.LoggerAdapter): diff --git a/src/griffe/_internal/merger.py b/packages/griffelib/src/griffelib/_internal/merger.py similarity index 95% rename from src/griffe/_internal/merger.py rename to packages/griffelib/src/griffelib/_internal/merger.py index 798ebf08e..d95eaa1d2 100644 --- a/src/griffe/_internal/merger.py +++ b/packages/griffelib/src/griffelib/_internal/merger.py @@ -5,11 +5,11 @@ from contextlib import suppress from typing import TYPE_CHECKING -from griffe._internal.exceptions import AliasResolutionError, CyclicAliasError -from griffe._internal.logger import logger +from griffelib._internal.exceptions import AliasResolutionError, CyclicAliasError +from griffelib._internal.logger import logger if TYPE_CHECKING: - from griffe._internal.models import Attribute, Class, Function, Module, Object, TypeAlias + from griffelib._internal.models import Attribute, Class, Function, Module, Object, TypeAlias def _merge_module_stubs(module: Module, stubs: Module) -> None: diff --git a/src/griffe/_internal/mixins.py b/packages/griffelib/src/griffelib/_internal/mixins.py similarity index 97% rename from src/griffe/_internal/mixins.py rename to packages/griffelib/src/griffelib/_internal/mixins.py index 05d69414c..b7455674c 100644 --- a/src/griffe/_internal/mixins.py +++ b/packages/griffelib/src/griffelib/_internal/mixins.py @@ -7,14 +7,14 @@ from contextlib import suppress from typing import TYPE_CHECKING, Any, TypeVar -from griffe._internal.enumerations import Kind -from griffe._internal.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError -from griffe._internal.merger import merge_stubs +from griffelib._internal.enumerations import Kind +from griffelib._internal.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError +from griffelib._internal.merger import merge_stubs if TYPE_CHECKING: from collections.abc import Sequence - from griffe._internal.models import Alias, Attribute, Class, Function, Module, Object, TypeAlias + from griffelib._internal.models import Alias, Attribute, Class, Function, Module, Object, TypeAlias _ObjType = TypeVar("_ObjType") @@ -222,7 +222,7 @@ def as_json(self, *, full: bool = False, **kwargs: Any) -> str: Returns: A JSON string. """ - from griffe._internal.encoders import JSONEncoder # Avoid circular import. # noqa: PLC0415 + from griffelib._internal.encoders import JSONEncoder # Avoid circular import. # noqa: PLC0415 return json.dumps(self, cls=JSONEncoder, full=full, **kwargs) @@ -241,7 +241,7 @@ def from_json(cls: type[_ObjType], json_string: str, **kwargs: Any) -> _ObjType: TypeError: When the json_string does not represent and object of the class from which this classmethod has been called. """ - from griffe._internal.encoders import json_decoder # Avoid circular import. # noqa: PLC0415 + from griffelib._internal.encoders import json_decoder # Avoid circular import. # noqa: PLC0415 kwargs.setdefault("object_hook", json_decoder) obj = json.loads(json_string, **kwargs) diff --git a/src/griffe/_internal/models.py b/packages/griffelib/src/griffelib/_internal/models.py similarity index 98% rename from src/griffe/_internal/models.py rename to packages/griffelib/src/griffelib/_internal/models.py index 9cc60e17f..ce254fddd 100644 --- a/src/griffe/_internal/models.py +++ b/packages/griffelib/src/griffelib/_internal/models.py @@ -11,21 +11,21 @@ from textwrap import dedent from typing import TYPE_CHECKING, Any, Callable, Literal, Union, cast -from griffe._internal.c3linear import c3linear_merge -from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle, parse -from griffe._internal.enumerations import Kind, ParameterKind, Parser, TypeParameterKind -from griffe._internal.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError, NameResolutionError -from griffe._internal.expressions import ExprCall, ExprName, ExprTuple -from griffe._internal.logger import logger -from griffe._internal.mixins import ObjectAliasMixin +from griffelib._internal.c3linear import c3linear_merge +from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle, parse +from griffelib._internal.enumerations import Kind, ParameterKind, Parser, TypeParameterKind +from griffelib._internal.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError, NameResolutionError +from griffelib._internal.expressions import ExprCall, ExprName, ExprTuple +from griffelib._internal.logger import logger +from griffelib._internal.mixins import ObjectAliasMixin if TYPE_CHECKING: from collections.abc import Sequence - from griffe._internal.collections import LinesCollection, ModulesCollection - from griffe._internal.docstrings.models import DocstringSection - from griffe._internal.expressions import Expr - from griffe._internal.git import GitInfo + from griffelib._internal.collections import LinesCollection, ModulesCollection + from griffelib._internal.docstrings.models import DocstringSection + from griffelib._internal.expressions import Expr + from griffelib._internal.git import GitInfo from functools import cached_property @@ -989,8 +989,8 @@ def module(self) -> Module: See also: [`package`][griffe.Object.package]. Examples: - >>> import griffe - >>> markdown = griffe.load("markdown") + >>> import griffelib + >>> markdown = griffelib.load("markdown") >>> markdown["core.Markdown.references"].module Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/core.py')) >>> # The `module` of a module is itself. @@ -1013,8 +1013,8 @@ def package(self) -> Module: See also: [`module`][griffe.Object.module]. Examples: - >>> import griffe - >>> markdown = griffe.load("markdown") + >>> import griffelib + >>> markdown = griffelib.load("markdown") >>> markdown["core.Markdown.references"].package Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/__init__.py')) """ @@ -1031,8 +1031,8 @@ def filepath(self) -> Path | list[Path]: [`relative_package_filepath`][griffe.Object.relative_package_filepath]. Examples: - >>> import griffe - >>> markdown = griffe.load("markdown") + >>> import griffelib + >>> markdown = griffelib.load("markdown") >>> markdown.filepath PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/__init__.py') """ @@ -1114,8 +1114,8 @@ def path(self) -> str: See also: [`canonical_path`][griffe.Object.canonical_path]. Examples: - >>> import griffe - >>> markdown = griffe.load("markdown") + >>> import griffelib + >>> markdown = griffelib.load("markdown") >>> markdown["core.Markdown.references"].path 'markdown.core.Markdown.references' """ diff --git a/src/griffe/_internal/py.typed b/packages/griffelib/src/griffelib/_internal/py.typed similarity index 100% rename from src/griffe/_internal/py.typed rename to packages/griffelib/src/griffelib/_internal/py.typed diff --git a/src/griffe/_internal/stats.py b/packages/griffelib/src/griffelib/_internal/stats.py similarity index 97% rename from src/griffe/_internal/stats.py rename to packages/griffelib/src/griffelib/_internal/stats.py index 957cc5c89..59400a510 100644 --- a/src/griffe/_internal/stats.py +++ b/packages/griffelib/src/griffelib/_internal/stats.py @@ -7,11 +7,11 @@ from pathlib import Path from typing import TYPE_CHECKING -from griffe._internal.enumerations import Kind +from griffelib._internal.enumerations import Kind if TYPE_CHECKING: - from griffe._internal.loader import GriffeLoader - from griffe._internal.models import Alias, Object + from griffelib._internal.loader import GriffeLoader + from griffelib._internal.models import Alias, Object class Stats: diff --git a/src/griffe/_internal/tests.py b/packages/griffelib/src/griffelib/_internal/tests.py similarity index 96% rename from src/griffe/_internal/tests.py rename to packages/griffelib/src/griffelib/_internal/tests.py index 912447056..1383bc7aa 100644 --- a/src/griffe/_internal/tests.py +++ b/packages/griffelib/src/griffelib/_internal/tests.py @@ -13,19 +13,19 @@ from textwrap import dedent from typing import TYPE_CHECKING -from griffe._internal.agents.inspector import inspect -from griffe._internal.agents.visitor import visit -from griffe._internal.collections import LinesCollection -from griffe._internal.loader import load -from griffe._internal.models import Module, Object +from griffelib._internal.agents.inspector import inspect +from griffelib._internal.agents.visitor import visit +from griffelib._internal.collections import LinesCollection +from griffelib._internal.loader import load +from griffelib._internal.models import Module, Object if TYPE_CHECKING: from collections.abc import Iterator, Mapping, Sequence - from griffe._internal.collections import ModulesCollection - from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle - from griffe._internal.enumerations import Parser - from griffe._internal.extensions.base import Extensions + from griffelib._internal.collections import ModulesCollection + from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle + from griffelib._internal.enumerations import Parser + from griffelib._internal.extensions.base import Extensions _TMPDIR_PREFIX = "griffe_" diff --git a/pyproject.toml b/pyproject.toml index f33dc1fc7..0a23924c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,7 @@ Gitter = "https://gitter.im/mkdocstrings/griffe" Funding = "https://github.com/sponsors/pawamoy" [project.scripts] -griffe = "griffe:main" +griffelib = "griffe:main" [tool.hatch.version] source = "code" diff --git a/scripts/griffe_exts.py b/scripts/griffe_exts.py index b9d0a5b5a..c324ce95e 100644 --- a/scripts/griffe_exts.py +++ b/scripts/griffe_exts.py @@ -2,20 +2,20 @@ from typing import Any -import griffe +import griffelib class ModuleGetAttrExtension(griffe.Extension): - def on_package(self, *, pkg: griffe.Module, **kwargs: Any) -> None: # noqa: ARG002,D102 + def on_package(self, *, pkg: griffelib.Module, **kwargs: Any) -> None: # noqa: ARG002,D102 if pkg.name == "griffe": - for name in griffe._deprecated_names: + for name in griffelib._deprecated_names: try: target = pkg[f"_internal.git._{name}"] except KeyError: # Old version where the utility was not yet renamed. continue - pkg.set_member(name, griffe.Alias(name, target=f"griffe._internal.git._{name}")) - admonition = griffe.DocstringSectionAdmonition( + pkg.set_member(name, griffelib.Alias(name, target=f"griffe._internal.git._{name}")) + admonition = griffelib.DocstringSectionAdmonition( kind="danger", text="", title="This function is deprecated and will become unavailable in the next major version.", diff --git a/src/griffe/__init__.py b/src/griffe/__init__.py index 21e9d8006..a48bb5aa2 100644 --- a/src/griffe/__init__.py +++ b/src/griffe/__init__.py @@ -1,642 +1,8 @@ -# This top-level module imports all public names from the package, -# and exposes them as public objects. We have tests to make sure -# no object is forgotten in this list. +"""Griffe CLI package. Re-exports griffelib and griffecli.""" -"""Griffe package. +from griffecli import * +from griffecli import __all__ as __cli_all__ +from griffelib import * +from griffelib import __all__ as __lib_all__ -Signatures for entire Python programs. -Extract the structure, the frame, the skeleton of your project, -to generate API documentation or find breaking changes in your API. - -The entirety of the public API is exposed here, in the top-level `griffe` module. - -All messages written to standard output or error are logged using the `logging` module. -Our logger's name is set to `"griffe"` and is public (you can rely on it). -You can obtain the logger from the standard `logging` module: `logging.getLogger("griffe")`. -Actual logging messages are not part of the public API (they might change without notice). - -Raised exceptions throughout the package are part of the public API (you can rely on them). -Their actual messages are not part of the public API (they might change without notice). - -The following paragraphs will help you discover the package's content. - -## CLI entrypoints - -Griffe provides a command-line interface (CLI) to interact with the package. The CLI entrypoints can be called from Python code. - -- [`griffe.main`][]: Run the main program. -- [`griffe.check`][]: Check for API breaking changes in two versions of the same package. -- [`griffe.dump`][]: Load packages data and dump it as JSON. - -## Loaders - -To load API data, Griffe provides several high-level functions. - -- [`griffe.load`][]: Load and return a Griffe object. -- [`griffe.load_git`][]: Load and return a module from a specific Git reference. -- [`griffe.load_pypi`][]: Load and return a module from a specific package version downloaded using pip. - -## Models - -The data loaded by Griffe is represented by several classes. - -- [`griffe.Module`][]: The class representing a Python module. -- [`griffe.Class`][]: The class representing a Python class. -- [`griffe.Function`][]: The class representing a Python function or method. -- [`griffe.Attribute`][]: The class representing a Python attribute. -- [`griffe.Alias`][]: This class represents an alias, or indirection, to an object declared in another module. - -Additional classes are available to represent other concepts. - -- [`griffe.Decorator`][]: This class represents a decorator. -- [`griffe.Parameters`][]: This class is a container for parameters. -- [`griffe.Parameter`][]: This class represent a function parameter. - -## Agents - -Griffe is able to analyze code both statically and dynamically, using the following "agents". -However most of the time you will only need to use the loaders above. - -- [`griffe.visit`][]: Parse and visit a module file. -- [`griffe.inspect`][]: Inspect a module. - -## Serializers - -Griffe can serizalize data to dictionary and JSON. - -- [`griffe.Object.as_json`][griffe.Object.as_json] -- [`griffe.Object.from_json`][griffe.Object.from_json] -- [`griffe.JSONEncoder`][]: JSON encoder for Griffe objects. -- [`griffe.json_decoder`][]: JSON decoder for Griffe objects. - -## API checks - -Griffe can compare two versions of the same package to find breaking changes. - -- [`griffe.find_breaking_changes`][]: Find breaking changes between two versions of the same API. -- [`griffe.Breakage`][]: Breakage classes can explain what broke from a version to another. - -## Extensions - -Griffe supports extensions. You can create your own extension by subclassing the `griffe.Extension` class. - -- [`griffe.load_extensions`][]: Load configured extensions. -- [`griffe.Extension`][]: Base class for Griffe extensions. - -## Docstrings - -Griffe can parse docstrings into structured data. - -Main class: - -- [`griffe.Docstring`][]: This class represents docstrings. - -Docstring section and element classes all start with `Docstring`. - -Docstring parsers: - -- [`griffe.parse`][]: Parse the docstring. -- [`griffe.parse_auto`][]: Parse a docstring by automatically detecting the style it uses. -- [`griffe.parse_google`][]: Parse a Google-style docstring. -- [`griffe.parse_numpy`][]: Parse a Numpydoc-style docstring. -- [`griffe.parse_sphinx`][]: Parse a Sphinx-style docstring. - -## Exceptions - -Griffe uses several exceptions to signal errors. - -- [`griffe.GriffeError`][]: The base exception for all Griffe errors. -- [`griffe.LoadingError`][]: Exception for loading errors. -- [`griffe.NameResolutionError`][]: Exception for names that cannot be resolved in a object scope. -- [`griffe.UnhandledEditableModuleError`][]: Exception for unhandled editables modules, when searching modules. -- [`griffe.UnimportableModuleError`][]: Exception for modules that cannot be imported. -- [`griffe.AliasResolutionError`][]: Exception for aliases that cannot be resolved. -- [`griffe.CyclicAliasError`][]: Exception raised when a cycle is detected in aliases. -- [`griffe.LastNodeError`][]: Exception raised when trying to access a next or previous node. -- [`griffe.RootNodeError`][]: Exception raised when trying to use siblings properties on a root node. -- [`griffe.BuiltinModuleError`][]: Exception raised when trying to access the filepath of a builtin module. -- [`griffe.ExtensionError`][]: Base class for errors raised by extensions. -- [`griffe.ExtensionNotLoadedError`][]: Exception raised when an extension could not be loaded. -- [`griffe.GitError`][]: Exception raised for errors related to Git. - -# Expressions - -Griffe stores snippets of code (attribute values, decorators, base class, type annotations) as expressions. -Expressions are basically abstract syntax trees (AST) with a few differences compared to the nodes returned by [`ast`][]. -Griffe provides a few helpers to extract expressions from regular AST nodes. - -- [`griffe.get_annotation`][]: Get a type annotation as expression. -- [`griffe.get_base_class`][]: Get a base class as expression. -- [`griffe.get_class_keyword`][]: Get a class keyword as expression. -- [`griffe.get_condition`][]: Get a condition as expression. -- [`griffe.get_expression`][]: Get an expression from an AST node. -- [`griffe.safe_get_annotation`][]: Get a type annotation as expression, safely (returns `None` on error). -- [`griffe.safe_get_base_class`][]: Get a base class as expression, safely (returns `None` on error). -- [`griffe.safe_get_class_keyword`][]: Get a class keyword as expression, safely (returns `None` on error). -- [`griffe.safe_get_condition`][]: Get a condition as expression, safely (returns `None` on error). -- [`griffe.safe_get_expression`][]: Get an expression from an AST node, safely (returns `None` on error). - -The base class for expressions. - -- [`griffe.Expr`][] - -Expression classes all start with `Expr`. - -# Loggers - -If you want to log messages from extensions, get a logger with `get_logger`. -The `logger` attribute is used by Griffe itself. You can use it to temporarily disable Griffe logging. - -- [`griffe.logger`][]: Our global logger, used throughout the library. -- [`griffe.get_logger`][]: Create and return a new logger instance. - -# Helpers - -To test your Griffe extensions, or to load API data from code in memory, Griffe provides the following helpers. - -- [`griffe.temporary_pyfile`][]: Create a Python file containing the given code in a temporary directory. -- [`griffe.temporary_pypackage`][]: Create a package containing the given modules in a temporary directory. -- [`griffe.temporary_visited_module`][]: Create and visit a temporary module with the given code. -- [`griffe.temporary_visited_package`][]: Create and visit a temporary package. -- [`griffe.temporary_inspected_module`][]: Create and inspect a temporary module with the given code. -- [`griffe.temporary_inspected_package`][]: Create and inspect a temporary package. -""" - -from __future__ import annotations - -import warnings -from typing import Any - -from griffe._internal.agents.inspector import Inspector, inspect -from griffe._internal.agents.nodes.assignments import get_instance_names, get_name, get_names -from griffe._internal.agents.nodes.ast import ( - ast_children, - ast_first_child, - ast_kind, - ast_last_child, - ast_next, - ast_next_siblings, - ast_previous, - ast_previous_siblings, - ast_siblings, -) -from griffe._internal.agents.nodes.docstrings import get_docstring - -# YORE: Bump 2: Replace `ExportedName, ` with `` within line. -from griffe._internal.agents.nodes.exports import ExportedName, get__all__, safe_get__all__ -from griffe._internal.agents.nodes.imports import relative_to_absolute -from griffe._internal.agents.nodes.parameters import ParametersType, get_parameters -from griffe._internal.agents.nodes.runtime import ObjectNode -from griffe._internal.agents.nodes.values import get_value, safe_get_value -from griffe._internal.agents.visitor import Visitor, builtin_decorators, stdlib_decorators, typing_overload, visit -from griffe._internal.c3linear import c3linear_merge -from griffe._internal.cli import DEFAULT_LOG_LEVEL, check, dump, get_parser, main -from griffe._internal.collections import LinesCollection, ModulesCollection -from griffe._internal.diff import ( - AttributeChangedTypeBreakage, - AttributeChangedValueBreakage, - Breakage, - ClassRemovedBaseBreakage, - ObjectChangedKindBreakage, - ObjectRemovedBreakage, - ParameterAddedRequiredBreakage, - ParameterChangedDefaultBreakage, - ParameterChangedKindBreakage, - ParameterChangedRequiredBreakage, - ParameterMovedBreakage, - ParameterRemovedBreakage, - ReturnChangedTypeBreakage, - find_breaking_changes, -) -from griffe._internal.docstrings.auto import ( - AutoOptions, - DocstringDetectionMethod, - PerStyleOptions, - infer_docstring_style, - parse_auto, -) -from griffe._internal.docstrings.google import GoogleOptions, parse_google -from griffe._internal.docstrings.models import ( - DocstringAdmonition, - DocstringAttribute, - DocstringClass, - DocstringDeprecated, - DocstringElement, - DocstringFunction, - DocstringModule, - DocstringNamedElement, - DocstringParameter, - DocstringRaise, - DocstringReceive, - DocstringReturn, - DocstringSection, - DocstringSectionAdmonition, - DocstringSectionAttributes, - DocstringSectionClasses, - DocstringSectionDeprecated, - DocstringSectionExamples, - DocstringSectionFunctions, - DocstringSectionModules, - DocstringSectionOtherParameters, - DocstringSectionParameters, - DocstringSectionRaises, - DocstringSectionReceives, - DocstringSectionReturns, - DocstringSectionText, - DocstringSectionTypeAliases, - DocstringSectionTypeParameters, - DocstringSectionWarns, - DocstringSectionYields, - DocstringTypeAlias, - DocstringTypeParameter, - DocstringWarn, - DocstringYield, -) -from griffe._internal.docstrings.numpy import NumpyOptions, parse_numpy -from griffe._internal.docstrings.parsers import ( - DocstringOptions, - DocstringStyle, - parse, - parsers, -) -from griffe._internal.docstrings.sphinx import SphinxOptions, parse_sphinx -from griffe._internal.docstrings.utils import docstring_warning, parse_docstring_annotation -from griffe._internal.encoders import JSONEncoder, json_decoder -from griffe._internal.enumerations import ( - BreakageKind, - DocstringSectionKind, - ExplanationStyle, - Kind, - LogLevel, - ObjectKind, - ParameterKind, - Parser, - TypeParameterKind, -) -from griffe._internal.exceptions import ( - AliasResolutionError, - BuiltinModuleError, - CyclicAliasError, - ExtensionError, - ExtensionNotLoadedError, - GitError, - GriffeError, - LastNodeError, - LoadingError, - NameResolutionError, - RootNodeError, - UnhandledEditableModuleError, - UnimportableModuleError, -) -from griffe._internal.expressions import ( - Expr, - ExprAttribute, - ExprBinOp, - ExprBoolOp, - ExprCall, - ExprCompare, - ExprComprehension, - ExprConstant, - ExprDict, - ExprDictComp, - ExprExtSlice, - ExprFormatted, - ExprGeneratorExp, - ExprIfExp, - ExprJoinedStr, - ExprKeyword, - ExprLambda, - ExprList, - ExprListComp, - ExprName, - ExprNamedExpr, - ExprParameter, - ExprSet, - ExprSetComp, - ExprSlice, - ExprSubscript, - ExprTuple, - ExprUnaryOp, - ExprVarKeyword, - ExprVarPositional, - ExprYield, - ExprYieldFrom, - get_annotation, - get_base_class, - get_class_keyword, - get_condition, - get_expression, - safe_get_annotation, - safe_get_base_class, - safe_get_class_keyword, - safe_get_condition, - safe_get_expression, -) -from griffe._internal.extensions.base import ( - Extension, - Extensions, - LoadableExtensionType, - builtin_extensions, - load_extensions, -) -from griffe._internal.extensions.dataclasses import DataclassesExtension -from griffe._internal.extensions.unpack_typeddict import UnpackTypedDictExtension -from griffe._internal.finder import ModuleFinder, NamePartsAndPathType, NamePartsType, NamespacePackage, Package -from griffe._internal.git import GitInfo, KnownGitService -from griffe._internal.importer import dynamic_import, sys_path -from griffe._internal.loader import GriffeLoader, load, load_git, load_pypi -from griffe._internal.logger import Logger, get_logger, logger, patch_loggers -from griffe._internal.merger import merge_stubs -from griffe._internal.mixins import ( - DelMembersMixin, - GetMembersMixin, - ObjectAliasMixin, - SerializationMixin, - SetMembersMixin, -) -from griffe._internal.models import ( - Alias, - Attribute, - Class, - Decorator, - Docstring, - Function, - Module, - Object, - Parameter, - Parameters, - TypeAlias, - TypeParameter, - TypeParameters, -) -from griffe._internal.stats import Stats -from griffe._internal.tests import ( - TmpPackage, - htree, - module_vtree, - temporary_inspected_module, - temporary_inspected_package, - temporary_pyfile, - temporary_pypackage, - temporary_visited_module, - temporary_visited_package, - vtree, -) - -# YORE: Bump 2: Remove block. -_deprecated_names = ( - "assert_git_repo", - "get_latest_tag", - "get_repo_root", - "tmp_worktree", -) - - -# YORE: Bump 2: Remove block. -def __getattr__(name: str) -> Any: - if name in _deprecated_names: - from griffe._internal import git # noqa: PLC0415 - - warnings.warn( - f"The `{name}` function is deprecated and will become unavailable in the next major version.", - DeprecationWarning, - stacklevel=2, - ) - return getattr(git, f"_{name}") - - raise AttributeError(f"module '{__name__}' has no attribute '{name}'") - - -# Regenerate this list with the following Python snippet: -# import griffe -# names = sorted(n for n in dir(griffe) if not n.startswith("_") and n not in ("Any", "annotations", "lazy_importing", "warnings")) -# print('__all__ = [\n "' + '",\n "'.join(names) + '",\n]') -__all__ = [ - "DEFAULT_LOG_LEVEL", - "Alias", - "AliasResolutionError", - "Attribute", - "AttributeChangedTypeBreakage", - "AttributeChangedValueBreakage", - "AutoOptions", - "Breakage", - "BreakageKind", - "BuiltinModuleError", - "Class", - "ClassRemovedBaseBreakage", - "CyclicAliasError", - "DataclassesExtension", - "Decorator", - "DelMembersMixin", - "Docstring", - "DocstringAdmonition", - "DocstringAttribute", - "DocstringClass", - "DocstringDeprecated", - "DocstringDetectionMethod", - "DocstringElement", - "DocstringFunction", - "DocstringModule", - "DocstringNamedElement", - "DocstringOptions", - "DocstringParameter", - "DocstringRaise", - "DocstringReceive", - "DocstringReturn", - "DocstringSection", - "DocstringSectionAdmonition", - "DocstringSectionAttributes", - "DocstringSectionClasses", - "DocstringSectionDeprecated", - "DocstringSectionExamples", - "DocstringSectionFunctions", - "DocstringSectionKind", - "DocstringSectionModules", - "DocstringSectionOtherParameters", - "DocstringSectionParameters", - "DocstringSectionRaises", - "DocstringSectionReceives", - "DocstringSectionReturns", - "DocstringSectionText", - "DocstringSectionTypeAliases", - "DocstringSectionTypeParameters", - "DocstringSectionWarns", - "DocstringSectionYields", - "DocstringStyle", - "DocstringTypeAlias", - "DocstringTypeParameter", - "DocstringWarn", - "DocstringYield", - "ExplanationStyle", - # YORE: Bump 2: Remove line. - "ExportedName", - "Expr", - "ExprAttribute", - "ExprBinOp", - "ExprBoolOp", - "ExprCall", - "ExprCompare", - "ExprComprehension", - "ExprConstant", - "ExprDict", - "ExprDictComp", - "ExprExtSlice", - "ExprFormatted", - "ExprGeneratorExp", - "ExprIfExp", - "ExprJoinedStr", - "ExprKeyword", - "ExprLambda", - "ExprList", - "ExprListComp", - "ExprName", - "ExprNamedExpr", - "ExprParameter", - "ExprSet", - "ExprSetComp", - "ExprSlice", - "ExprSubscript", - "ExprTuple", - "ExprUnaryOp", - "ExprVarKeyword", - "ExprVarPositional", - "ExprYield", - "ExprYieldFrom", - "Extension", - "ExtensionError", - "ExtensionNotLoadedError", - "Extensions", - "Function", - "GetMembersMixin", - "GitError", - "GitInfo", - "GoogleOptions", - "GriffeError", - "GriffeLoader", - "Inspector", - "JSONEncoder", - "Kind", - "KnownGitService", - "LastNodeError", - "LinesCollection", - "LoadableExtensionType", - "LoadingError", - "LogLevel", - "Logger", - "Module", - "ModuleFinder", - "ModulesCollection", - "NamePartsAndPathType", - "NamePartsType", - "NameResolutionError", - "NamespacePackage", - "NumpyOptions", - "Object", - "ObjectAliasMixin", - "ObjectChangedKindBreakage", - "ObjectKind", - "ObjectNode", - "ObjectRemovedBreakage", - "Package", - "Parameter", - "ParameterAddedRequiredBreakage", - "ParameterChangedDefaultBreakage", - "ParameterChangedKindBreakage", - "ParameterChangedRequiredBreakage", - "ParameterKind", - "ParameterMovedBreakage", - "ParameterRemovedBreakage", - "Parameters", - "ParametersType", - "Parser", - "PerStyleOptions", - "ReturnChangedTypeBreakage", - "RootNodeError", - "SerializationMixin", - "SetMembersMixin", - "SphinxOptions", - "Stats", - "TmpPackage", - "TypeAlias", - "TypeParameter", - "TypeParameterKind", - "TypeParameters", - "UnhandledEditableModuleError", - "UnimportableModuleError", - "UnpackTypedDictExtension", - "Visitor", - "assert_git_repo", - "ast_children", - "ast_first_child", - "ast_kind", - "ast_last_child", - "ast_next", - "ast_next_siblings", - "ast_previous", - "ast_previous_siblings", - "ast_siblings", - "builtin_decorators", - "builtin_extensions", - "c3linear_merge", - "check", - "docstring_warning", - "dump", - "dynamic_import", - "find_breaking_changes", - "get__all__", - "get_annotation", - "get_base_class", - "get_class_keyword", - "get_condition", - "get_docstring", - "get_expression", - "get_instance_names", - "get_latest_tag", - "get_logger", - "get_name", - "get_names", - "get_parameters", - "get_parser", - "get_repo_root", - "get_value", - "htree", - "infer_docstring_style", - "inspect", - "json_decoder", - "load", - "load_extensions", - "load_git", - "load_pypi", - "logger", - "main", - "merge_stubs", - "module_vtree", - "parse", - "parse_auto", - "parse_docstring_annotation", - "parse_google", - "parse_numpy", - "parse_sphinx", - "parsers", - "patch_loggers", - "relative_to_absolute", - "safe_get__all__", - "safe_get_annotation", - "safe_get_base_class", - "safe_get_class_keyword", - "safe_get_condition", - "safe_get_expression", - "safe_get_value", - "stdlib_decorators", - "sys_path", - "temporary_inspected_module", - "temporary_inspected_package", - "temporary_pyfile", - "temporary_pypackage", - "temporary_visited_module", - "temporary_visited_package", - "tmp_worktree", - "typing_overload", - "visit", - "vtree", -] +__all__ = [*__lib_all__, *__cli_all__] diff --git a/src/griffe/__main__.py b/src/griffe/__main__.py index a9047c9b9..3b5ca458b 100644 --- a/src/griffe/__main__.py +++ b/src/griffe/__main__.py @@ -1,13 +1,6 @@ -# Entry-point module, in case you use `python -m griffe`. -# -# Why does this file exist, and why `__main__`? For more info, read: -# -# - https://www.python.org/dev/peps/pep-0338/ -# - https://docs.python.org/3/using/cmdline.html#cmdoption-m - import sys -from griffe._internal.cli import main +from griffecli import main if __name__ == "__main__": sys.exit(main(sys.argv[1:])) diff --git a/tests/helpers.py b/tests/helpers.py index 47613ddd0..1ca06eaef 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -6,7 +6,7 @@ import sys from tempfile import gettempdir -from griffe._internal.tests import _TMPDIR_PREFIX +from griffelib._internal.tests import _TMPDIR_PREFIX def clear_sys_modules(name: str | None = None) -> None: diff --git a/tests/test_api.py b/tests/test_api.py index 6fad5e4ad..a86028d6c 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -10,15 +10,15 @@ import pytest from mkdocstrings import Inventory -import griffe +import griffelib if TYPE_CHECKING: from collections.abc import Iterator @pytest.fixture(name="loader", scope="module") -def _fixture_loader() -> griffe.GriffeLoader: - loader = griffe.GriffeLoader( +def _fixture_loader() -> griffelib.GriffeLoader: + loader = griffelib.GriffeLoader( extensions=griffe.load_extensions( "griffe_inherited_docstrings", # YORE: Bump 2: Remove line. @@ -32,23 +32,23 @@ def _fixture_loader() -> griffe.GriffeLoader: @pytest.fixture(name="internal_api", scope="module") -def _fixture_internal_api(loader: griffe.GriffeLoader) -> griffe.Module: +def _fixture_internal_api(loader: griffelib.GriffeLoader) -> griffelib.Module: return loader.modules_collection["griffe._internal"] @pytest.fixture(name="public_api", scope="module") -def _fixture_public_api(loader: griffe.GriffeLoader) -> griffe.Module: +def _fixture_public_api(loader: griffelib.GriffeLoader) -> griffelib.Module: return loader.modules_collection["griffe"] def _yield_public_objects( - obj: griffe.Module | griffe.Class, + obj: griffelib.Module | griffelib.Class, *, modules: bool = False, modulelevel: bool = True, inherited: bool = False, special: bool = False, -) -> Iterator[griffe.Object | griffe.Alias]: +) -> Iterator[griffe.Object | griffelib.Alias]: for member in obj.all_members.values() if inherited else obj.members.values(): try: if member.is_module: @@ -74,22 +74,22 @@ def _yield_public_objects( inherited=inherited, special=special, ) - except (griffe.AliasResolutionError, griffe.CyclicAliasError): + except (griffe.AliasResolutionError, griffelib.CyclicAliasError): continue @pytest.fixture(name="modulelevel_internal_objects", scope="module") -def _fixture_modulelevel_internal_objects(internal_api: griffe.Module) -> list[griffe.Object | griffe.Alias]: +def _fixture_modulelevel_internal_objects(internal_api: griffelib.Module) -> list[griffe.Object | griffelib.Alias]: return list(_yield_public_objects(internal_api, modulelevel=True)) @pytest.fixture(name="internal_objects", scope="module") -def _fixture_internal_objects(internal_api: griffe.Module) -> list[griffe.Object | griffe.Alias]: +def _fixture_internal_objects(internal_api: griffelib.Module) -> list[griffe.Object | griffelib.Alias]: return list(_yield_public_objects(internal_api, modulelevel=False, special=True)) @pytest.fixture(name="public_objects", scope="module") -def _fixture_public_objects(public_api: griffe.Module) -> list[griffe.Object | griffe.Alias]: +def _fixture_public_objects(public_api: griffelib.Module) -> list[griffe.Object | griffelib.Alias]: return list(_yield_public_objects(public_api, modulelevel=False, inherited=True, special=True)) @@ -102,7 +102,7 @@ def _fixture_inventory() -> Inventory: return Inventory.parse_sphinx(file) -def test_alias_proxies(internal_api: griffe.Module) -> None: +def test_alias_proxies(internal_api: griffelib.Module) -> None: """The Alias class has all the necessary methods and properties.""" alias_members = set(internal_api["models.Alias"].all_members.keys()) for cls in ( @@ -116,17 +116,17 @@ def test_alias_proxies(internal_api: griffe.Module) -> None: assert name in alias_members -def test_exposed_objects(modulelevel_internal_objects: list[griffe.Object | griffe.Alias]) -> None: +def test_exposed_objects(modulelevel_internal_objects: list[griffe.Object | griffelib.Alias]) -> None: """All public objects in the internal API are exposed under `griffe`.""" not_exposed = [ obj.path for obj in modulelevel_internal_objects - if obj.name not in griffe.__all__ or not hasattr(griffe, obj.name) + if obj.name not in griffelib.__all__ or not hasattr(griffe, obj.name) ] assert not not_exposed, "Objects not exposed:\n" + "\n".join(sorted(not_exposed)) -def test_unique_names(modulelevel_internal_objects: list[griffe.Object | griffe.Alias]) -> None: +def test_unique_names(modulelevel_internal_objects: list[griffe.Object | griffelib.Alias]) -> None: """All internal objects have unique names.""" names_to_paths = defaultdict(list) for obj in modulelevel_internal_objects: @@ -135,14 +135,14 @@ def test_unique_names(modulelevel_internal_objects: list[griffe.Object | griffe. assert not non_unique, "Non-unique names:\n" + "\n".join(str(paths) for paths in non_unique) -def test_single_locations(public_api: griffe.Module) -> None: +def test_single_locations(public_api: griffelib.Module) -> None: """All objects have a single public location.""" - def _public_path(obj: griffe.Object | griffe.Alias) -> bool: + def _public_path(obj: griffelib.Object | griffelib.Alias) -> bool: return obj.is_public and (obj.parent is None or _public_path(obj.parent)) multiple_locations = {} - for obj_name in griffe.__all__: + for obj_name in griffelib.__all__: obj = public_api[obj_name] if obj.aliases and ( public_aliases := [path for path, alias in obj.aliases.items() if path != obj.path and _public_path(alias)] @@ -153,7 +153,7 @@ def _public_path(obj: griffe.Object | griffe.Alias) -> bool: ) -def test_api_matches_inventory(inventory: Inventory, public_objects: list[griffe.Object | griffe.Alias]) -> None: +def test_api_matches_inventory(inventory: Inventory, public_objects: list[griffe.Object | griffelib.Alias]) -> None: """All public objects are added to the inventory.""" ignore_names = {"__getattr__", "__init__", "__repr__", "__str__", "__post_init__"} ignore_paths = {"griffe.DataclassesExtension.*", "griffe.UnpackTypedDictExtension.*"} @@ -172,8 +172,8 @@ def test_api_matches_inventory(inventory: Inventory, public_objects: list[griffe def test_inventory_matches_api( inventory: Inventory, - public_objects: list[griffe.Object | griffe.Alias], - loader: griffe.GriffeLoader, + public_objects: list[griffe.Object | griffelib.Alias], + loader: griffelib.GriffeLoader, ) -> None: """The inventory doesn't contain any additional Python object.""" not_in_api = [] @@ -188,14 +188,14 @@ def test_inventory_matches_api( assert not not_in_api, msg.format(paths="\n".join(sorted(not_in_api))) -def test_no_module_docstrings_in_internal_api(internal_api: griffe.Module) -> None: +def test_no_module_docstrings_in_internal_api(internal_api: griffelib.Module) -> None: """No module docstrings should be written in our internal API. The reasoning is that docstrings are addressed to users of the public API, but internal modules are not exposed to users, so they should not have docstrings. """ - def _modules(obj: griffe.Module) -> Iterator[griffe.Module]: + def _modules(obj: griffelib.Module) -> Iterator[griffe.Module]: for member in obj.modules.values(): yield member yield from _modules(member) diff --git a/tests/test_cli.py b/tests/test_cli.py index a71507a76..c500a3ac2 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -6,7 +6,7 @@ import pytest -from griffe._internal import cli, debug +from griffelib._internal import cli, debug def test_main() -> None: diff --git a/tests/test_diff.py b/tests/test_diff.py index 726b888ed..840649521 100644 --- a/tests/test_diff.py +++ b/tests/test_diff.py @@ -4,7 +4,7 @@ import pytest -from griffe import Breakage, BreakageKind, find_breaking_changes, temporary_visited_module, temporary_visited_package +from griffelib import Breakage, BreakageKind, find_breaking_changes, temporary_visited_module, temporary_visited_package @pytest.mark.parametrize( diff --git a/tests/test_docstrings/conftest.py b/tests/test_docstrings/conftest.py index 366727cee..c37dfda55 100644 --- a/tests/test_docstrings/conftest.py +++ b/tests/test_docstrings/conftest.py @@ -6,7 +6,7 @@ import pytest -from griffe._internal.docstrings import google, numpy, sphinx +from griffelib._internal.docstrings import google, numpy, sphinx from tests.test_docstrings.helpers import ParserType, parser if TYPE_CHECKING: diff --git a/tests/test_docstrings/helpers.py b/tests/test_docstrings/helpers.py index 3fd9aa64a..113032fb3 100644 --- a/tests/test_docstrings/helpers.py +++ b/tests/test_docstrings/helpers.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Any, Protocol, Union -from griffe import ( +from griffelib import ( Attribute, Class, Docstring, diff --git a/tests/test_docstrings/test_google.py b/tests/test_docstrings/test_google.py index 0af072c6d..ee456d6a8 100644 --- a/tests/test_docstrings/test_google.py +++ b/tests/test_docstrings/test_google.py @@ -7,7 +7,7 @@ import pytest -from griffe import ( +from griffelib import ( Attribute, Class, Docstring, diff --git a/tests/test_docstrings/test_numpy.py b/tests/test_docstrings/test_numpy.py index 344856e50..4532d8e5c 100644 --- a/tests/test_docstrings/test_numpy.py +++ b/tests/test_docstrings/test_numpy.py @@ -7,7 +7,7 @@ import pytest -from griffe import ( +from griffelib import ( Attribute, Class, Docstring, diff --git a/tests/test_docstrings/test_sphinx.py b/tests/test_docstrings/test_sphinx.py index 992ff1565..a02dc784e 100644 --- a/tests/test_docstrings/test_sphinx.py +++ b/tests/test_docstrings/test_sphinx.py @@ -7,7 +7,7 @@ import pytest -from griffe import ( +from griffelib import ( Attribute, Class, DocstringAttribute, diff --git a/tests/test_docstrings/test_warnings.py b/tests/test_docstrings/test_warnings.py index 219eb508f..7c85d01e9 100644 --- a/tests/test_docstrings/test_warnings.py +++ b/tests/test_docstrings/test_warnings.py @@ -2,7 +2,7 @@ from __future__ import annotations -from griffe import Docstring, Function, Parameter, ParameterKind, Parameters, Parser, parse +from griffelib import Docstring, Function, Parameter, ParameterKind, Parameters, Parser, parse def test_can_warn_without_parent_module() -> None: diff --git a/tests/test_encoders.py b/tests/test_encoders.py index b8d3eeb47..47a779144 100644 --- a/tests/test_encoders.py +++ b/tests/test_encoders.py @@ -8,7 +8,7 @@ import pytest from jsonschema import ValidationError, validate -from griffe import ( +from griffelib import ( Attribute, Class, Function, diff --git a/tests/test_expressions.py b/tests/test_expressions.py index 872412d92..31315bac4 100644 --- a/tests/test_expressions.py +++ b/tests/test_expressions.py @@ -7,7 +7,7 @@ import pytest -from griffe import Module, Parser, get_expression, temporary_visited_module +from griffelib import Module, Parser, get_expression, temporary_visited_module from tests.test_nodes import syntax_examples diff --git a/tests/test_extensions/test_base.py b/tests/test_extensions/test_base.py index b3dce656e..deecc6069 100644 --- a/tests/test_extensions/test_base.py +++ b/tests/test_extensions/test_base.py @@ -8,7 +8,7 @@ import pytest -from griffe import ( +from griffelib import ( Alias, Extension, GriffeLoader, @@ -19,12 +19,12 @@ temporary_visited_module, temporary_visited_package, ) -from griffe._internal.models import Attribute, Class, Function, Module, Object, TypeAlias +from griffelib._internal.models import Attribute, Class, Function, Module, Object, TypeAlias if TYPE_CHECKING: import ast - from griffe import Attribute, Class, Function, Module, Object, ObjectNode, TypeAlias + from griffelib import Attribute, Class, Function, Module, Object, ObjectNode, TypeAlias class AnalysisEventsTest(Extension): # noqa: D101 diff --git a/tests/test_extensions/test_dataclasses.py b/tests/test_extensions/test_dataclasses.py index 147f6ff43..c8021cc88 100644 --- a/tests/test_extensions/test_dataclasses.py +++ b/tests/test_extensions/test_dataclasses.py @@ -1,6 +1,6 @@ """Test the dataclasses extension.""" -from griffe import ParameterKind, load_extensions, temporary_visited_package +from griffelib import ParameterKind, load_extensions, temporary_visited_package def test_dataclass_support() -> None: diff --git a/tests/test_extensions/test_unpack_typeddict.py b/tests/test_extensions/test_unpack_typeddict.py index fa24d9036..d7d8dbf0f 100644 --- a/tests/test_extensions/test_unpack_typeddict.py +++ b/tests/test_extensions/test_unpack_typeddict.py @@ -1,6 +1,6 @@ """Test the unpack extension.""" -from griffe import DocstringSectionKind, load_extensions, temporary_visited_package +from griffelib import DocstringSectionKind, load_extensions, temporary_visited_package def test_typeddict_support() -> None: diff --git a/tests/test_finder.py b/tests/test_finder.py index 9b6d34076..a7afcba39 100644 --- a/tests/test_finder.py +++ b/tests/test_finder.py @@ -8,8 +8,8 @@ import pytest -from griffe import Module, ModuleFinder, NamespacePackage, Package, temporary_pypackage -from griffe._internal.finder import _handle_editable_module, _handle_pth_file +from griffelib import Module, ModuleFinder, NamespacePackage, Package, temporary_pypackage +from griffelib._internal.finder import _handle_editable_module, _handle_pth_file @pytest.mark.parametrize( @@ -125,7 +125,7 @@ def test_editables_file_handling(tmp_path: Path, editable_file_name: str) -> Non tmp_path: Pytest fixture. """ pth_file = tmp_path / editable_file_name - pth_file.write_text("hello\nF.map_module('griffe', 'src/griffe/__init__.py')", encoding="utf8") + pth_file.write_text("hello\nF.map_module('griffe', 'packages/griffe/src/griffe/__init__.py')", encoding="utf8") paths = [sp.path for sp in _handle_editable_module(pth_file)] assert paths == [Path("src")] @@ -139,7 +139,7 @@ def test_setuptools_file_handling(tmp_path: Path, annotation: str) -> None: annotation: The type annotation of the MAPPING variable. """ pth_file = tmp_path / "__editable__whatever.py" - pth_file.write_text(f"hello\nMAPPING{annotation} = {{'griffe': 'src/griffe'}}", encoding="utf8") + pth_file.write_text(f"hello\nMAPPING{annotation} = {{'griffe': 'packages/griffe/src/griffe'}}", encoding="utf8") paths = [sp.path for sp in _handle_editable_module(pth_file)] assert paths == [Path("src")] diff --git a/tests/test_functions.py b/tests/test_functions.py index 3afe89adb..391d2f553 100644 --- a/tests/test_functions.py +++ b/tests/test_functions.py @@ -4,7 +4,7 @@ import pytest -from griffe import ParameterKind, temporary_visited_module +from griffelib import ParameterKind, temporary_visited_module def test_visit_simple_function() -> None: diff --git a/tests/test_git.py b/tests/test_git.py index 6b5f541e9..2d954d9df 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -1,4 +1,4 @@ -"""Tests for creating a griffe Module from specific commits in a git repository.""" +"""Tests for creating a griffelib Module from specific commits in a git repository.""" from __future__ import annotations @@ -8,7 +8,7 @@ import pytest -from griffe import Module, check, load_git +from griffelib import Module, check, load_git from tests import FIXTURES_DIR if TYPE_CHECKING: diff --git a/tests/test_inheritance.py b/tests/test_inheritance.py index 7d76a8dce..ec9a8f041 100644 --- a/tests/test_inheritance.py +++ b/tests/test_inheritance.py @@ -6,10 +6,10 @@ import pytest -from griffe import ModulesCollection, temporary_inspected_module, temporary_visited_module +from griffelib import ModulesCollection, temporary_inspected_module, temporary_visited_module if TYPE_CHECKING: - from griffe import Class + from griffelib import Class def _mro_paths(cls: Class) -> list[str]: diff --git a/tests/test_inspector.py b/tests/test_inspector.py index ffce822a1..005c012b0 100644 --- a/tests/test_inspector.py +++ b/tests/test_inspector.py @@ -6,7 +6,7 @@ import pytest -from griffe import ( +from griffelib import ( Expr, TypeParameterKind, inspect, diff --git a/tests/test_loader.py b/tests/test_loader.py index 9d79cdbd7..74558b19f 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -8,7 +8,7 @@ import pytest -from griffe import ( +from griffelib import ( ExprName, GriffeLoader, temporary_inspected_package, @@ -20,7 +20,7 @@ if TYPE_CHECKING: from pathlib import Path - from griffe import Alias + from griffelib import Alias def test_has_docstrings_does_not_try_to_resolve_alias() -> None: diff --git a/tests/test_merger.py b/tests/test_merger.py index ce6aae421..320bf3689 100644 --- a/tests/test_merger.py +++ b/tests/test_merger.py @@ -2,7 +2,7 @@ from __future__ import annotations -from griffe import temporary_visited_package +from griffelib import temporary_visited_package def test_dont_trigger_alias_resolution_when_merging_stubs() -> None: diff --git a/tests/test_mixins.py b/tests/test_mixins.py index 30fdc68a0..3f1c4ee15 100644 --- a/tests/test_mixins.py +++ b/tests/test_mixins.py @@ -2,7 +2,7 @@ from __future__ import annotations -from griffe import module_vtree +from griffelib import module_vtree def test_access_members_using_string_and_tuples() -> None: diff --git a/tests/test_models.py b/tests/test_models.py index 7684fccf2..a4c92f7ea 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -8,7 +8,7 @@ import pytest -from griffe import ( +from griffelib import ( Attribute, Class, Docstring, diff --git a/tests/test_nodes.py b/tests/test_nodes.py index 27cfcc53c..1a3efe4c6 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -7,7 +7,7 @@ import pytest -from griffe import Expr, ExprName, module_vtree, relative_to_absolute, temporary_visited_module +from griffelib import Expr, ExprName, module_vtree, relative_to_absolute, temporary_visited_module syntax_examples = [ # Operations. diff --git a/tests/test_public_api.py b/tests/test_public_api.py index 3c92b11a3..a189f0b3c 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -1,6 +1,6 @@ """Tests for public API handling.""" -from griffe import temporary_visited_module +from griffelib import temporary_visited_module def test_not_detecting_imported_objects_as_public() -> None: diff --git a/tests/test_stdlib.py b/tests/test_stdlib.py index 5c5eaea87..7861eb5b0 100644 --- a/tests/test_stdlib.py +++ b/tests/test_stdlib.py @@ -8,12 +8,12 @@ import pytest -from griffe import GriffeLoader, LoadingError +from griffelib import GriffeLoader, LoadingError if TYPE_CHECKING: from collections.abc import Iterator - from griffe import Alias, Object + from griffelib import Alias, Object def _access_inherited_members(obj: Object | Alias) -> None: diff --git a/tests/test_visitor.py b/tests/test_visitor.py index b1d9d44b9..c930a6e28 100644 --- a/tests/test_visitor.py +++ b/tests/test_visitor.py @@ -7,7 +7,7 @@ import pytest -from griffe import ( +from griffelib import ( Expr, GriffeLoader, TypeParameterKind, From 9707557d13fd536d2f1caf4baae4a2d9c7b9c248 Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 15:03:18 +0100 Subject: [PATCH 02/10] Add griffecli init --- packages/griffecli/src/griffecli/__init__.py | 10 ++++- packages/griffelib/src/griffelib/__init__.py | 39 ++++++++++++++------ 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/packages/griffecli/src/griffecli/__init__.py b/packages/griffecli/src/griffecli/__init__.py index 54cec7a60..406930b03 100644 --- a/packages/griffecli/src/griffecli/__init__.py +++ b/packages/griffecli/src/griffecli/__init__.py @@ -1 +1,9 @@ -# TODO: Cut proper imports from griffelib `__init__.py` module +from griffecli._internal.cli import DEFAULT_LOG_LEVEL, check, dump, get_parser, main + +__all__ = [ + "DEFAULT_LOG_LEVEL", + "check", + "dump", + "get_parser", + "main", +] diff --git a/packages/griffelib/src/griffelib/__init__.py b/packages/griffelib/src/griffelib/__init__.py index 8b93293da..d2a9665ef 100644 --- a/packages/griffelib/src/griffelib/__init__.py +++ b/packages/griffelib/src/griffelib/__init__.py @@ -168,7 +168,11 @@ from typing import Any from griffelib._internal.agents.inspector import Inspector, inspect -from griffelib._internal.agents.nodes.assignments import get_instance_names, get_name, get_names +from griffelib._internal.agents.nodes.assignments import ( + get_instance_names, + get_name, + get_names, +) from griffelib._internal.agents.nodes.ast import ( ast_children, ast_first_child, @@ -183,14 +187,23 @@ from griffelib._internal.agents.nodes.docstrings import get_docstring # YORE: Bump 2: Replace `ExportedName, ` with `` within line. -from griffelib._internal.agents.nodes.exports import ExportedName, get__all__, safe_get__all__ +from griffelib._internal.agents.nodes.exports import ( + ExportedName, + get__all__, + safe_get__all__, +) from griffelib._internal.agents.nodes.imports import relative_to_absolute from griffelib._internal.agents.nodes.parameters import ParametersType, get_parameters from griffelib._internal.agents.nodes.runtime import ObjectNode from griffelib._internal.agents.nodes.values import get_value, safe_get_value -from griffelib._internal.agents.visitor import Visitor, builtin_decorators, stdlib_decorators, typing_overload, visit +from griffelib._internal.agents.visitor import ( + Visitor, + builtin_decorators, + stdlib_decorators, + typing_overload, + visit, +) from griffelib._internal.c3linear import c3linear_merge -from griffecli._internal.cli import DEFAULT_LOG_LEVEL, check, dump, get_parser, main from griffelib._internal.collections import LinesCollection, ModulesCollection from griffelib._internal.diff import ( AttributeChangedTypeBreakage, @@ -260,7 +273,10 @@ parsers, ) from griffelib._internal.docstrings.sphinx import SphinxOptions, parse_sphinx -from griffelib._internal.docstrings.utils import docstring_warning, parse_docstring_annotation +from griffelib._internal.docstrings.utils import ( + docstring_warning, + parse_docstring_annotation, +) from griffelib._internal.encoders import JSONEncoder, json_decoder from griffelib._internal.enumerations import ( BreakageKind, @@ -341,7 +357,13 @@ ) from griffelib._internal.extensions.dataclasses import DataclassesExtension from griffelib._internal.extensions.unpack_typeddict import UnpackTypedDictExtension -from griffelib._internal.finder import ModuleFinder, NamePartsAndPathType, NamePartsType, NamespacePackage, Package +from griffelib._internal.finder import ( + ModuleFinder, + NamePartsAndPathType, + NamePartsType, + NamespacePackage, + Package, +) from griffelib._internal.git import GitInfo, KnownGitService from griffelib._internal.importer import dynamic_import, sys_path from griffelib._internal.loader import GriffeLoader, load, load_git, load_pypi @@ -412,7 +434,6 @@ def __getattr__(name: str) -> Any: # names = sorted(n for n in dir(griffe) if not n.startswith("_") and n not in ("Any", "annotations", "lazy_importing", "warnings")) # print('__all__ = [\n "' + '",\n "'.join(names) + '",\n]') __all__ = [ - "DEFAULT_LOG_LEVEL", "Alias", "AliasResolutionError", "Attribute", @@ -578,9 +599,7 @@ def __getattr__(name: str) -> Any: "builtin_decorators", "builtin_extensions", "c3linear_merge", - "check", "docstring_warning", - "dump", "dynamic_import", "find_breaking_changes", "get__all__", @@ -596,7 +615,6 @@ def __getattr__(name: str) -> Any: "get_name", "get_names", "get_parameters", - "get_parser", "get_repo_root", "get_value", "htree", @@ -608,7 +626,6 @@ def __getattr__(name: str) -> Any: "load_git", "load_pypi", "logger", - "main", "merge_stubs", "module_vtree", "parse", From 3acc03ebf7fb3046b1bba0d7bc36813311e4144b Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 15:57:57 +0100 Subject: [PATCH 03/10] Reformat --- packages/griffecli/src/griffecli/_internal/cli.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/griffecli/src/griffecli/_internal/cli.py b/packages/griffecli/src/griffecli/_internal/cli.py index 877d8db89..091f47ffa 100644 --- a/packages/griffecli/src/griffecli/_internal/cli.py +++ b/packages/griffecli/src/griffecli/_internal/cli.py @@ -23,7 +23,6 @@ from typing import IO, TYPE_CHECKING, Any, Callable import colorama - from griffelib._internal import debug from griffelib._internal.diff import find_breaking_changes from griffelib._internal.encoders import JSONEncoder @@ -138,7 +137,9 @@ def get_parser() -> argparse.ArgumentParser: description = "Signatures for entire Python programs. " "Extract the structure, the frame, the skeleton of your project, " "to generate API documentation or find breaking changes in your API." - parser = argparse.ArgumentParser(add_help=False, usage=usage, description=description, prog="griffe") + parser = argparse.ArgumentParser( + add_help=False, usage=usage, description=description, prog="griffe" + ) main_help = "Show this help message and exit. Commands also accept the -h/--help option." subcommand_help = "Show this help message and exit." From 3225cc1f90985e68f0b482efe0771b8ecd88dab2 Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 15:26:39 +0100 Subject: [PATCH 04/10] Configure workspace --- packages/griffecli/pyproject.toml | 12 ++++--- packages/griffelib/pyproject.toml | 1 + pyproject.toml | 59 +++++++++++++++++-------------- 3 files changed, 41 insertions(+), 31 deletions(-) diff --git a/packages/griffecli/pyproject.toml b/packages/griffecli/pyproject.toml index cf6e80d23..808002f22 100644 --- a/packages/griffecli/pyproject.toml +++ b/packages/griffecli/pyproject.toml @@ -41,8 +41,12 @@ classifiers = [ "Typing :: Typed", ] -[tool.hatch.metadata.hooks.uv-dynamic-versioning] +[project.scripts] +griffe = "griffecli:main" -[tool.hatch.metadata.hooks.uv-dynamic-versioning.optional-dependencies] - -[tool.hatch.build.targets.sdist] +[tool.hatch.build.targets.wheel] +# Manual pages can be included in the wheel. +# Depending on the installation tool, they will be accessible to users. +# pipx supports it, uv does not yet, see https://github.com/astral-sh/uv/issues/4731. +sources = ["src/"] +artifacts = ["share/**/*"] diff --git a/packages/griffelib/pyproject.toml b/packages/griffelib/pyproject.toml index 280d86cfe..16aa7b5d6 100644 --- a/packages/griffelib/pyproject.toml +++ b/packages/griffelib/pyproject.toml @@ -44,5 +44,6 @@ classifiers = [ [tool.hatch.metadata.hooks.uv-dynamic-versioning] [tool.hatch.metadata.hooks.uv-dynamic-versioning.optional-dependencies] +pypi = ["pip>=24.0", "platformdirs>=4.2", "wheel>=0.42"] [tool.hatch.build.targets.sdist] diff --git a/pyproject.toml b/pyproject.toml index 0a23924c9..69cf3fc67 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,19 +1,30 @@ [build-system] # pdm-backend is left here as a dependency of the version discovery script currently in use. # It may be removed in the future. See mkdocstrings/griffe#430 -requires = ["hatchling", "pdm-backend"] +requires = ["hatchling", "pdm-backend", "uv-dynamic-versioning>=0.7.0"] build-backend = "hatchling.build" +[tool.hatch.version] +source = "code" +path = "scripts/get_version.py" +expression = "get_version()" + [project] name = "griffe" description = "Signatures for entire Python programs. Extract the structure, the frame, the skeleton of your project, to generate API documentation or find breaking changes in your API." -authors = [{name = "Timothée Mazzucotelli", email = "dev@pawamoy.fr"}] +authors = [{ name = "Timothée Mazzucotelli", email = "dev@pawamoy.fr" }] license = "ISC" license-files = ["LICENSE"] readme = "README.md" requires-python = ">=3.10" -keywords = ["api", "signature", "breaking-changes", "static-analysis", "dynamic-analysis"] -dynamic = ["version"] +keywords = [ + "api", + "signature", + "breaking-changes", + "static-analysis", + "dynamic-analysis", +] +dynamic = ["version", "dependencies", "optional-dependencies"] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", @@ -36,16 +47,12 @@ classifiers = [ "Topic :: Utilities", "Typing :: Typed", ] -dependencies = [ - "colorama>=0.4", -] -[project.optional-dependencies] -pypi = [ - "pip>=24.0", - "platformdirs>=4.2", - "wheel>=0.42", -] +[tool.hatch.metadata.hooks.uv-dynamic-versioning] +dependencies = ["griffecli=={{version}}", "griffelib=={{version}}"] + +[tool.hatch.metadata.hooks.uv-dynamic-versioning.optional-dependencies] +pypi = ["griffelib[pypi]=={{version}}"] [project.urls] Homepage = "https://mkdocstrings.github.io/griffe" @@ -58,23 +65,19 @@ Gitter = "https://gitter.im/mkdocstrings/griffe" Funding = "https://github.com/sponsors/pawamoy" [project.scripts] -griffelib = "griffe:main" - -[tool.hatch.version] -source = "code" -path = "scripts/get_version.py" -expression = "get_version()" +griffe = "griffecli:main" [tool.hatch.build] # Include as much as possible in the source distribution, to help redistributors. ignore-vcs = true -exclude = [".github", ".pdm-build"] +exclude = [".github"] [tool.hatch.build.targets.sdist] include = [ "config", "docs", "scripts", + "packages", "src", "share", "tests", @@ -92,12 +95,7 @@ sources = ["src/"] artifacts = ["share/**/*"] [dependency-groups] -maintain = [ - "build>=1.2", - "git-changelog>=2.5", - "twine>=5.1", - "yore>=0.3.3", -] +maintain = ["build>=1.2", "git-changelog>=2.5", "twine>=5.1", "yore>=0.3.3"] ci = [ "duty>=1.6", "griffe-inherited-docstrings>=1.1.2", @@ -114,7 +112,7 @@ ci = [ "types-markdown>=3.6", "types-pyyaml>=6.0", ] - docs = [ +docs = [ "code2flow>=2.5", "griffe-inherited-docstrings>=1.1.2", "markdown-callouts>=0.4", @@ -136,3 +134,10 @@ ci = [ [tool.uv] default-groups = ["maintain", "ci", "docs"] + +[tool.uv.workspace] +members = ["packages/*"] + +[tool.uv.sources] +griffelib = { workspace = true } +griffecli = { workspace = true } From 976e03832d9f52778519699df22ee5f233c1bcbd Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 15:27:44 +0100 Subject: [PATCH 05/10] Reformat everything --- tests/test_api.py | 3 +-- tests/test_cli.py | 1 - tests/test_diff.py | 1 - tests/test_docstrings/conftest.py | 2 +- tests/test_docstrings/test_google.py | 1 - tests/test_docstrings/test_numpy.py | 1 - tests/test_docstrings/test_sphinx.py | 1 - tests/test_encoders.py | 3 +-- tests/test_expressions.py | 2 +- tests/test_extensions/test_base.py | 1 - tests/test_finder.py | 1 - tests/test_functions.py | 1 - tests/test_git.py | 2 +- tests/test_inheritance.py | 1 - tests/test_inspector.py | 20 +++++++++++++++----- tests/test_loader.py | 1 - tests/test_models.py | 1 - tests/test_nodes.py | 1 - tests/test_stdlib.py | 1 - tests/test_visitor.py | 1 - 20 files changed, 20 insertions(+), 26 deletions(-) diff --git a/tests/test_api.py b/tests/test_api.py index a86028d6c..64450cc81 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -7,11 +7,10 @@ from pathlib import Path from typing import TYPE_CHECKING +import griffelib import pytest from mkdocstrings import Inventory -import griffelib - if TYPE_CHECKING: from collections.abc import Iterator diff --git a/tests/test_cli.py b/tests/test_cli.py index c500a3ac2..e8ec3e908 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -5,7 +5,6 @@ import sys import pytest - from griffelib._internal import cli, debug diff --git a/tests/test_diff.py b/tests/test_diff.py index 840649521..8468b72f2 100644 --- a/tests/test_diff.py +++ b/tests/test_diff.py @@ -3,7 +3,6 @@ from __future__ import annotations import pytest - from griffelib import Breakage, BreakageKind, find_breaking_changes, temporary_visited_module, temporary_visited_package diff --git a/tests/test_docstrings/conftest.py b/tests/test_docstrings/conftest.py index c37dfda55..5e862ce67 100644 --- a/tests/test_docstrings/conftest.py +++ b/tests/test_docstrings/conftest.py @@ -5,8 +5,8 @@ from typing import TYPE_CHECKING import pytest - from griffelib._internal.docstrings import google, numpy, sphinx + from tests.test_docstrings.helpers import ParserType, parser if TYPE_CHECKING: diff --git a/tests/test_docstrings/test_google.py b/tests/test_docstrings/test_google.py index ee456d6a8..828121357 100644 --- a/tests/test_docstrings/test_google.py +++ b/tests/test_docstrings/test_google.py @@ -6,7 +6,6 @@ from typing import TYPE_CHECKING import pytest - from griffelib import ( Attribute, Class, diff --git a/tests/test_docstrings/test_numpy.py b/tests/test_docstrings/test_numpy.py index 4532d8e5c..08651c897 100644 --- a/tests/test_docstrings/test_numpy.py +++ b/tests/test_docstrings/test_numpy.py @@ -6,7 +6,6 @@ from typing import TYPE_CHECKING import pytest - from griffelib import ( Attribute, Class, diff --git a/tests/test_docstrings/test_sphinx.py b/tests/test_docstrings/test_sphinx.py index a02dc784e..5e4af02a3 100644 --- a/tests/test_docstrings/test_sphinx.py +++ b/tests/test_docstrings/test_sphinx.py @@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Any import pytest - from griffelib import ( Attribute, Class, diff --git a/tests/test_encoders.py b/tests/test_encoders.py index 47a779144..196205b52 100644 --- a/tests/test_encoders.py +++ b/tests/test_encoders.py @@ -6,8 +6,6 @@ import sys import pytest -from jsonschema import ValidationError, validate - from griffelib import ( Attribute, Class, @@ -19,6 +17,7 @@ temporary_inspected_package, temporary_visited_module, ) +from jsonschema import ValidationError, validate def test_minimal_data_is_enough() -> None: diff --git a/tests/test_expressions.py b/tests/test_expressions.py index 31315bac4..efbcfd223 100644 --- a/tests/test_expressions.py +++ b/tests/test_expressions.py @@ -6,8 +6,8 @@ import sys import pytest - from griffelib import Module, Parser, get_expression, temporary_visited_module + from tests.test_nodes import syntax_examples diff --git a/tests/test_extensions/test_base.py b/tests/test_extensions/test_base.py index deecc6069..f0a086135 100644 --- a/tests/test_extensions/test_base.py +++ b/tests/test_extensions/test_base.py @@ -7,7 +7,6 @@ from typing import TYPE_CHECKING, Any import pytest - from griffelib import ( Alias, Extension, diff --git a/tests/test_finder.py b/tests/test_finder.py index a7afcba39..53da5aafe 100644 --- a/tests/test_finder.py +++ b/tests/test_finder.py @@ -7,7 +7,6 @@ from textwrap import dedent import pytest - from griffelib import Module, ModuleFinder, NamespacePackage, Package, temporary_pypackage from griffelib._internal.finder import _handle_editable_module, _handle_pth_file diff --git a/tests/test_functions.py b/tests/test_functions.py index 391d2f553..175313a7b 100644 --- a/tests/test_functions.py +++ b/tests/test_functions.py @@ -3,7 +3,6 @@ from __future__ import annotations import pytest - from griffelib import ParameterKind, temporary_visited_module diff --git a/tests/test_git.py b/tests/test_git.py index 2d954d9df..6993e41af 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -7,8 +7,8 @@ from typing import TYPE_CHECKING import pytest - from griffelib import Module, check, load_git + from tests import FIXTURES_DIR if TYPE_CHECKING: diff --git a/tests/test_inheritance.py b/tests/test_inheritance.py index ec9a8f041..f0b36578f 100644 --- a/tests/test_inheritance.py +++ b/tests/test_inheritance.py @@ -5,7 +5,6 @@ from typing import TYPE_CHECKING, Callable import pytest - from griffelib import ModulesCollection, temporary_inspected_module, temporary_visited_module if TYPE_CHECKING: diff --git a/tests/test_inspector.py b/tests/test_inspector.py index 005c012b0..1310ddfa8 100644 --- a/tests/test_inspector.py +++ b/tests/test_inspector.py @@ -5,7 +5,6 @@ import sys import pytest - from griffelib import ( Expr, TypeParameterKind, @@ -14,6 +13,7 @@ temporary_inspected_package, temporary_pypackage, ) + from tests.helpers import clear_sys_modules @@ -28,7 +28,9 @@ def test_annotations_from_builtin_types() -> None: def test_annotations_from_classes() -> None: """Assert custom classes are correctly transformed to annotations.""" - with temporary_inspected_module("class A: pass\ndef func(a: A) -> A: pass") as module: + with temporary_inspected_module( + "class A: pass\ndef func(a: A) -> A: pass", + ) as module: func = module["func"] assert func.parameters[0].name == "a" param = func.parameters[0].annotation @@ -40,7 +42,10 @@ def test_annotations_from_classes() -> None: # YORE: EOL 3.13: Remove block. -@pytest.mark.skipif(sys.version_info >= (3, 14), reason="3.14 changes type annotations, see test below") +@pytest.mark.skipif( + sys.version_info >= (3, 14), + reason="3.14 changes type annotations, see test below", +) @pytest.mark.parametrize( ("annotation", "expected"), [ @@ -104,7 +109,10 @@ def method(self, p: StringIO): def test_missing_dependency() -> None: """Assert missing dependencies are handled during dynamic imports.""" with ( - pytest.raises(ImportError, match="ModuleNotFoundError: No module named 'missing'"), + pytest.raises( + ImportError, + match="ModuleNotFoundError: No module named 'missing'", + ), temporary_inspected_module("import missing"), ): pass @@ -143,7 +151,9 @@ def test_inspecting_module_importing_other_module() -> None: def test_inspecting_parameters_with_functions_as_default_values() -> None: """Assert functions as default parameter values are serialized with their name.""" - with temporary_inspected_module("def func(): ...\ndef other_func(f=func): ...") as module: + with temporary_inspected_module( + "def func(): ...\ndef other_func(f=func): ...", + ) as module: default = module["other_func"].parameters["f"].default assert default == "func" diff --git a/tests/test_loader.py b/tests/test_loader.py index 74558b19f..9552ef8f6 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -7,7 +7,6 @@ from typing import TYPE_CHECKING import pytest - from griffelib import ( ExprName, GriffeLoader, diff --git a/tests/test_models.py b/tests/test_models.py index a4c92f7ea..abbdfd512 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -7,7 +7,6 @@ from textwrap import dedent import pytest - from griffelib import ( Attribute, Class, diff --git a/tests/test_nodes.py b/tests/test_nodes.py index 1a3efe4c6..add23a5cc 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -6,7 +6,6 @@ from ast import PyCF_ONLY_AST import pytest - from griffelib import Expr, ExprName, module_vtree, relative_to_absolute, temporary_visited_module syntax_examples = [ diff --git a/tests/test_stdlib.py b/tests/test_stdlib.py index 7861eb5b0..ae47a9698 100644 --- a/tests/test_stdlib.py +++ b/tests/test_stdlib.py @@ -7,7 +7,6 @@ from typing import TYPE_CHECKING import pytest - from griffelib import GriffeLoader, LoadingError if TYPE_CHECKING: diff --git a/tests/test_visitor.py b/tests/test_visitor.py index c930a6e28..2930ab128 100644 --- a/tests/test_visitor.py +++ b/tests/test_visitor.py @@ -6,7 +6,6 @@ from textwrap import dedent import pytest - from griffelib import ( Expr, GriffeLoader, From 155ff29e60a787ef58ce31ca8cc497117135902f Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 16:05:07 +0100 Subject: [PATCH 06/10] Fix proj name --- packages/griffelib/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/griffelib/pyproject.toml b/packages/griffelib/pyproject.toml index 16aa7b5d6..9f90de2a2 100644 --- a/packages/griffelib/pyproject.toml +++ b/packages/griffelib/pyproject.toml @@ -10,7 +10,7 @@ path = "../../scripts/get_version.py" expression = "get_version()" [project] -name = "griffe" +name = "griffelib" description = "The griffelib library" authors = [{name = "Timothée Mazzucotelli", email = "dev@pawamoy.fr"}] license = "ISC" From f9f9c5ec168805f808498c9b3db84589c95875e1 Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 16:06:52 +0100 Subject: [PATCH 07/10] Fix NameError --- scripts/griffe_exts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/griffe_exts.py b/scripts/griffe_exts.py index c324ce95e..81c1e87f9 100644 --- a/scripts/griffe_exts.py +++ b/scripts/griffe_exts.py @@ -5,7 +5,7 @@ import griffelib -class ModuleGetAttrExtension(griffe.Extension): +class ModuleGetAttrExtension(griffelib.Extension): def on_package(self, *, pkg: griffelib.Module, **kwargs: Any) -> None: # noqa: ARG002,D102 if pkg.name == "griffe": for name in griffelib._deprecated_names: From de91615d929148fbd1088eaf4cef620a906087eb Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 16:19:52 +0100 Subject: [PATCH 08/10] Crossref fixes --- CHANGELOG.md | 44 +- .../official/warnings-deprecated.md | 2 +- docs/guide/users/checking.md | 2 +- docs/guide/users/extending.md | 82 ++-- docs/guide/users/how-to/parse-docstrings.md | 2 +- .../guide/users/how-to/selectively-inspect.md | 2 +- docs/guide/users/how-to/support-decorators.md | 4 +- docs/guide/users/loading.md | 26 +- docs/guide/users/navigating.md | 166 +++---- .../users/recommendations/public-apis.md | 2 +- docs/guide/users/serializing.md | 10 +- docs/introduction.md | 4 +- docs/reference/api/agents.md | 62 +-- docs/reference/api/cli.md | 8 +- docs/reference/api/expressions.md | 2 +- docs/reference/api/models.md | 12 +- docs/reference/api/serializers.md | 2 +- packages/griffelib/src/griffelib/__init__.py | 126 +++--- .../griffelib/_internal/agents/inspector.py | 8 +- .../_internal/agents/nodes/exports.py | 2 +- .../src/griffelib/_internal/agents/visitor.py | 6 +- .../griffelib/_internal/docstrings/auto.py | 2 +- .../src/griffelib/_internal/encoders.py | 2 +- .../src/griffelib/_internal/expressions.py | 2 +- .../griffelib/_internal/extensions/base.py | 2 +- .../src/griffelib/_internal/finder.py | 4 +- .../griffelib/src/griffelib/_internal/git.py | 2 +- .../src/griffelib/_internal/importer.py | 2 +- .../src/griffelib/_internal/loader.py | 26 +- .../src/griffelib/_internal/logger.py | 2 +- .../src/griffelib/_internal/models.py | 424 +++++++++--------- tests/test_api.py | 32 +- tests/test_docstrings/test_google.py | 2 +- tests/test_docstrings/test_numpy.py | 2 +- tests/test_docstrings/test_sphinx.py | 2 +- 35 files changed, 553 insertions(+), 527 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcc5b52e3..8bc4e1ea6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Deprecations - The `on_alias` event's signature changed from `on_alias(self, *, node: AST | ObjectNode, alias: Alias, agent: Visitor | Inspector, **kwargs)` (an [analysis event][analysis-events]) to `on_alias(self, *, alias: Alias, loader: GriffeLoader, **kwargs)` ([a load event][load-events]). Use the new signature, or rename your method to `on_alias_instance` to keep the old signature (`on_alias_instance` is a new analysis event that replaces the old `on_alias` one). Backward compatibility is maintained until next major version. -- The `on_wildcard_expansion` event is deprecated. Instead, use the `on_alias` event, and check the [`wildcard_imported`][griffe.Alias.wildcard_imported] boolean attribute of aliases. +- The `on_wildcard_expansion` event is deprecated. Instead, use the `on_alias` event, and check the [`wildcard_imported`][griffelib.Alias.wildcard_imported] boolean attribute of aliases. - The `on_package_loaded` event is renamed to `on_package`. Backward compatibility is maintained until next major version. - The use of previously exposed Git-related utilities (`assert_git_repo`, `get_repo_root`, `get_latest_tag` and `tmp_worktree`) is deprecated, as they are not a core part of the library's functionality. These utilities are now part of our internal API. @@ -498,10 +498,10 @@ WARNING: **⚡ Imminent v1! ⚡🚀 See [v0.46](#0460-2024-06-16).** ### Deprecations - All submodules are deprecated. All objects are now exposed in the top-level `griffe` module. -- All logger names are deprecated, and will be replaced with `"griffe"` in v1. In v1 our single `"griffe"` logger will provide a method to temporarily disable logging, [`logger.disable()`][griffe.Logger.disable], since that's the most common third-party use. +- All logger names are deprecated, and will be replaced with `"griffe"` in v1. In v1 our single `"griffe"` logger will provide a method to temporarily disable logging, [`logger.disable()`][griffelib.Logger.disable], since that's the most common third-party use. - The `get_logger` function is deprecated. Instead, we'll use a global `logger` internally, and users are welcome to use it too. - The `patch_loggers` function is renamed `patch_logger`. -- Following the logging changes, the [`docstring_warning`][griffe.docstring_warning] function can now directly log a warning message instead of returning a callable that does. Passing it a logger name (to get a callable) is deprecated in favor of passing it a docstring, message and offset directly. +- Following the logging changes, the [`docstring_warning`][griffelib.docstring_warning] function can now directly log a warning message instead of returning a callable that does. Passing it a logger name (to get a callable) is deprecated in favor of passing it a docstring, message and offset directly. ### Features @@ -571,16 +571,16 @@ We are working on v1, and it will come soon, so we recommend that you consider a We are still in v0, so no major bump yet. -- Calling objects' [`has_labels()`][griffe.Object.has_labels] method with a `labels` keyword argument is not supported anymore. The parameter became a variadic positional parameter, so it cannot be used as a keyword argument anymore. Passing a sequence instead of multiple positional arguments still works but will emit a deprecation warning. -- Calling the [`load_extensions()`][griffe.load_extensions] function with an `exts` keyword argument is not supported anymore. The parameter became a variadic positional parameter, so it cannot be used as a keyword argument anymore. Passing a sequence instead of multiple positional arguments still works but will emit a deprecation warning. +- Calling objects' [`has_labels()`][griffelib.Object.has_labels] method with a `labels` keyword argument is not supported anymore. The parameter became a variadic positional parameter, so it cannot be used as a keyword argument anymore. Passing a sequence instead of multiple positional arguments still works but will emit a deprecation warning. +- Calling the [`load_extensions()`][griffelib.load_extensions] function with an `exts` keyword argument is not supported anymore. The parameter became a variadic positional parameter, so it cannot be used as a keyword argument anymore. Passing a sequence instead of multiple positional arguments still works but will emit a deprecation warning. ### Deprecations -- As seen above in the breaking changes section, the only parameters of [`Object.has_labels()`][griffe.Object.has_labels] and [`load_extensions()`][griffe.load_extensions] both became variadic positional parameters. Passing a sequence as single argument is deprecated in favor of passing multiple arguments. This is an ergonomic change: I myself often forgot to wrap extensions in a list. Passing sequences of labels (lists, sets, tuples) is also difficult from Jinja templates. -- The following methods and properties on objects and aliases are deprecated: `member_is_exported()`, `is_explicitely_exported`, `is_implicitely_exported`. Use the [`is_exported`][griffe.ObjectAliasMixin.is_exported] property instead. See [issue 281](https://github.com/mkdocstrings/griffe/issues/281). -- The [`is_exported()`][griffe.ObjectAliasMixin.is_exported] and [`is_public()`][griffe.ObjectAliasMixin.is_public] methods became properties. They can still be called like methods, but will emit deprecation warnings when doing so. See [issue 281](https://github.com/mkdocstrings/griffe/issues/281). -- The `ignore_private` parameter of the [`find_breaking_changes()`][griffe.find_breaking_changes] function is now deprecated and unused. With the reworked "exported" and "public" API, this parameter became useless. See [issue 281](https://github.com/mkdocstrings/griffe/issues/281). -- Using `stats()` instead of [`Stats`][griffe.Stats] will now emit a deprecation warning. +- As seen above in the breaking changes section, the only parameters of [`Object.has_labels()`][griffelib.Object.has_labels] and [`load_extensions()`][griffelib.load_extensions] both became variadic positional parameters. Passing a sequence as single argument is deprecated in favor of passing multiple arguments. This is an ergonomic change: I myself often forgot to wrap extensions in a list. Passing sequences of labels (lists, sets, tuples) is also difficult from Jinja templates. +- The following methods and properties on objects and aliases are deprecated: `member_is_exported()`, `is_explicitely_exported`, `is_implicitely_exported`. Use the [`is_exported`][griffelib.ObjectAliasMixin.is_exported] property instead. See [issue 281](https://github.com/mkdocstrings/griffe/issues/281). +- The [`is_exported()`][griffelib.ObjectAliasMixin.is_exported] and [`is_public()`][griffelib.ObjectAliasMixin.is_public] methods became properties. They can still be called like methods, but will emit deprecation warnings when doing so. See [issue 281](https://github.com/mkdocstrings/griffe/issues/281). +- The `ignore_private` parameter of the [`find_breaking_changes()`][griffelib.find_breaking_changes] function is now deprecated and unused. With the reworked "exported" and "public" API, this parameter became useless. See [issue 281](https://github.com/mkdocstrings/griffe/issues/281). +- Using `stats()` instead of [`Stats`][griffelib.Stats] will now emit a deprecation warning. ### Features @@ -1062,7 +1062,7 @@ We are still in v0, so no major bump yet. ### Deprecations - Classes `InspectorExtension` and `VisitorExtension` - are deprecated in favor of [`Extension`][griffe.Extension]. + are deprecated in favor of [`Extension`][griffelib.Extension]. As a side-effect, the `hybrid` extension is also deprecated. See [how to use and write extensions](guide/users/extending.md). @@ -1077,7 +1077,7 @@ We are still in v0, so no major bump yet. - Function `load_extension` was removed (made private) - Function `patch_ast` was removed - Function `tmp_worktree` was removed (made private) -- Type [`Extension`][griffe.Extension] is now a class +- Type [`Extension`][griffelib.Extension] is now a class ### Features @@ -1113,9 +1113,9 @@ We are still in v0, so no major bump yet. - Drop support for Python 3.7 - API changes: - - [`GriffeLoader.resolve_aliases(only_exported)`][griffe.GriffeLoader.resolve_aliases]: Deprecated parameter was removed and replaced by `implicit` (inverse semantics) - - [`GriffeLoader.resolve_aliases(only_known_modules)`][griffe.GriffeLoader.resolve_aliases]: Deprecated parameter was removed and replaced by `external` (inverse semantics) - - [`LinesCollection.tokens`][griffe.LinesCollection]: Public object was removed (Python 3.7) + - [`GriffeLoader.resolve_aliases(only_exported)`][griffelib.GriffeLoader.resolve_aliases]: Deprecated parameter was removed and replaced by `implicit` (inverse semantics) + - [`GriffeLoader.resolve_aliases(only_known_modules)`][griffelib.GriffeLoader.resolve_aliases]: Deprecated parameter was removed and replaced by `external` (inverse semantics) + - [`LinesCollection.tokens`][griffelib.LinesCollection]: Public object was removed (Python 3.7) - `ASTNode.end_lineno`: Public object was removed (Python 3.7) - `griffe.agents.extensions`: Deprecated module was removed and replaced by `griffe.extensions` @@ -1387,7 +1387,7 @@ We are still in v0, so no major bump yet. [Compare with 0.24.1](https://github.com/mkdocstrings/griffe/compare/0.24.1...0.25.0) ### Breaking changes -- Parameter `only_known_modules` was renamed `external` in the [`expand_wildcards()`][griffe.GriffeLoader.expand_wildcards] method of the loader. +- Parameter `only_known_modules` was renamed `external` in the [`expand_wildcards()`][griffelib.GriffeLoader.expand_wildcards] method of the loader. - Exception `UnhandledEditablesModuleError` was renamed `UnhandledEditableModuleError` since we now support editable installation from other packages than `editables`. ### Highlights @@ -1443,18 +1443,18 @@ for the initial code allowing to compare two Griffe trees. ### Breaking Changes -- All parameters of the [`load_git`][griffe.load_git] function, except `module`, are now keyword-only. -- Parameter `try_relative_path` of the [`load_git`][griffe.load_git] function was removed. -- Parameter `commit` was renamed `ref` in the [`load_git`][griffe.load_git] function. +- All parameters of the [`load_git`][griffelib.load_git] function, except `module`, are now keyword-only. +- Parameter `try_relative_path` of the [`load_git`][griffelib.load_git] function was removed. +- Parameter `commit` was renamed `ref` in the [`load_git`][griffelib.load_git] function. - Parameter `commit` was renamed `ref` in the `tmp_worktree` helper, which will probably become private later. - Parameters `ref` and `repo` switched positions in the `tmp_worktree` helper. -- All parameters of the [`resolve_aliases`][griffe.GriffeLoader.resolve_aliases] method are now keyword-only. -- Parameters `only_exported` and `only_known_modules` of the [`resolve_module_aliases`][griffe.GriffeLoader.resolve_module_aliases] +- All parameters of the [`resolve_aliases`][griffelib.GriffeLoader.resolve_aliases] method are now keyword-only. +- Parameters `only_exported` and `only_known_modules` of the [`resolve_module_aliases`][griffelib.GriffeLoader.resolve_module_aliases] method were removed. This method is most probably not used by anyone, and will probably be made private in the future. ### Deprecations -- Parameters `only_exported` and `only_known_modules` of the [`resolve_aliases`][griffe.GriffeLoader.resolve_aliases] +- Parameters `only_exported` and `only_known_modules` of the [`resolve_aliases`][griffelib.GriffeLoader.resolve_aliases] method are deprecated in favor of their inverted counter-part `implicit` and `external` parameters. - Example before: `loader.resolve_aliases(only_exported=True, only_known_modules=True)` diff --git a/docs/extensions/official/warnings-deprecated.md b/docs/extensions/official/warnings-deprecated.md index 61ff9ddb2..10ea7f78b 100644 --- a/docs/extensions/official/warnings-deprecated.md +++ b/docs/extensions/official/warnings-deprecated.md @@ -7,7 +7,7 @@ --- -This extension adds support for functions and classes decorated with [`@warnings.deprecated(...)`][warnings.deprecated], as implemented thanks to [PEP 702](https://peps.python.org/pep-0702/). The message provided in the decorator call will be stored in the corresponding Griffe object's [`deprecated`][griffe.Object.deprecated] attribute (usable by downstream rendering templates), and will also add an admonition to the object's docstring with the provided message as text. +This extension adds support for functions and classes decorated with [`@warnings.deprecated(...)`][warnings.deprecated], as implemented thanks to [PEP 702](https://peps.python.org/pep-0702/). The message provided in the decorator call will be stored in the corresponding Griffe object's [`deprecated`][griffelib.Object.deprecated] attribute (usable by downstream rendering templates), and will also add an admonition to the object's docstring with the provided message as text. ```python from warnings import deprecated diff --git a/docs/guide/users/checking.md b/docs/guide/users/checking.md index 9594fafd5..38c4792c0 100644 --- a/docs/guide/users/checking.md +++ b/docs/guide/users/checking.md @@ -80,7 +80,7 @@ Griffe will actually install packages in a cache directory. It means a few thing ## Python API -To programmatically check for API breaking changes, you have to load two snapshots of your code base, for example using our [`load_git()`][griffe.load_git] utility, and then passing them both to the [`find_breaking_changes()`][griffe.find_breaking_changes] function. This function will yield instances of [`Breakage`][griffe.Breakage]. It's up to you how you want to use these breakage instances. +To programmatically check for API breaking changes, you have to load two snapshots of your code base, for example using our [`load_git()`][griffelib.load_git] utility, and then passing them both to the [`find_breaking_changes()`][griffelib.find_breaking_changes] function. This function will yield instances of [`Breakage`][griffelib.Breakage]. It's up to you how you want to use these breakage instances. ```python import griffe diff --git a/docs/guide/users/extending.md b/docs/guide/users/extending.md index 9aa408731..8eebb1483 100644 --- a/docs/guide/users/extending.md +++ b/docs/guide/users/extending.md @@ -47,9 +47,9 @@ In the above two examples, `pydantic` would be a built-in extension, `scripts/ex ### Programmatically -Within Python code, extensions can be specified with the `extensions` parameter of the [`GriffeLoader` class][griffe.GriffeLoader] or [`load` function][griffe.load]. +Within Python code, extensions can be specified with the `extensions` parameter of the [`GriffeLoader` class][griffelib.GriffeLoader] or [`load` function][griffelib.load]. -The parameter accepts an instance of the [`Extensions` class][griffe.Extensions]. Such an instance is created with the help of the [`load_extensions` function][griffe.load_extensions], which itself accepts a list of strings, dictionaries, extension classes and extension instances. +The parameter accepts an instance of the [`Extensions` class][griffelib.Extensions]. Such an instance is created with the help of the [`load_extensions` function][griffelib.load_extensions], which itself accepts a list of strings, dictionaries, extension classes and extension instances. Strings and dictionaries are used the same way as [on the command-line](#on-the-command-line). Extension instances are used as such, and extension classes are instantiated without any options. @@ -88,7 +88,7 @@ plugins: - griffe_attrs ``` -The `extensions` key accepts a list that is passed to the [`load_extensions` function][griffe.load_extensions]. See [how to use extensions programmatically](#programmatically) to learn more. +The `extensions` key accepts a list that is passed to the [`load_extensions` function][griffelib.load_extensions]. See [how to use extensions programmatically](#programmatically) to learn more. ## Writing extensions @@ -100,9 +100,9 @@ To extract information from your Python sources, Griffe tries to build Abstract If the source code is not available (the modules are built-in or compiled), Griffe imports the modules and builds object trees instead. -Griffe then follows the [Visitor pattern](https://www.wikiwand.com/en/Visitor_pattern) to walk the tree and extract information. For ASTs, Griffe uses its [Visitor agent][griffe.Visitor] and for object trees, it uses its [Inspector agent][griffe.Inspector]. +Griffe then follows the [Visitor pattern](https://www.wikiwand.com/en/Visitor_pattern) to walk the tree and extract information. For ASTs, Griffe uses its [Visitor agent][griffelib.Visitor] and for object trees, it uses its [Inspector agent][griffelib.Inspector]. -Sometimes during the walk through the source or runtime objects, both the visitor and inspector agents will trigger events, called **analysis events**. These events can be hooked on by extensions to alter or enhance Griffe's behavior. Some hooks will be passed just the current node being visited, others will be passed both the node and an instance of an [Object][griffe.Object] subclass, such as a [Module][griffe.Module], a [Class][griffe.Class], a [Function][griffe.Function], an [Attribute][griffe.Attribute], or a [Type Alias][griffe.TypeAlias]. Extensions will therefore be able to modify these instances. +Sometimes during the walk through the source or runtime objects, both the visitor and inspector agents will trigger events, called **analysis events**. These events can be hooked on by extensions to alter or enhance Griffe's behavior. Some hooks will be passed just the current node being visited, others will be passed both the node and an instance of an [Object][griffelib.Object] subclass, such as a [Module][griffelib.Module], a [Class][griffelib.Class], a [Function][griffelib.Function], an [Attribute][griffelib.Attribute], or a [Type Alias][griffelib.TypeAlias]. Extensions will therefore be able to modify these instances. Once the Griffe tree for a given package has been fully constructed, Griffe will trigger a second set of events, called **load events**, by walking the tree again. **It is safer to use load events as they are triggered only once data is complete for a given package**, contrary to the analysis events which are triggered *while the Griffe tree is still being built*. @@ -114,7 +114,7 @@ M(Module definition) --- C(Class definition) & F(Function definition) C --- m(Function definition) & A(Variable assignment) ``` -The following flow chart shows an example of an object tree inspection. The tree is simplified as well: [many more types of objects are handled][griffe.ObjectKind]. +The following flow chart shows an example of an object tree inspection. The tree is simplified as well: [many more types of objects are handled][griffelib.ObjectKind]. ```mermaid flowchart TB @@ -125,9 +125,9 @@ C --- m(Method) & A(Attribute) For a more concrete example, let say that we visit (or inspect) an AST (or object tree) for a given module, and that this module contains a single class, which itself contains a single method: - the agent (visitor or inspector) will walk through the tree by starting with the module node -- it will instantiate a [Module][griffe.Module], then walk through its members, continuing with the class node -- it will instantiate a [Class][griffe.Class], then walk through its members, continuing with the function node -- it will instantiate a [Function][griffe.Function] +- it will instantiate a [Module][griffelib.Module], then walk through its members, continuing with the class node +- it will instantiate a [Class][griffelib.Class], then walk through its members, continuing with the function node +- it will instantiate a [Function][griffelib.Function] - then it will go back up and finish walking since there are no more nodes to walk through Every time the agent enters a node, creates an object instance, or finishes handling members of an object, it will trigger an event. @@ -198,17 +198,17 @@ There are two kinds of events in Griffe: [**load events**](#load-events) and [** There is 1 generic **load event**: -- [`on_object`][griffe.Extension.on_object]: The "on object" event is triggered on any kind of object (except for aliases and packages, so modules, classes, functions, attributes and type aliases), once the tree for the object's package has been fully constructed. +- [`on_object`][griffelib.Extension.on_object]: The "on object" event is triggered on any kind of object (except for aliases and packages, so modules, classes, functions, attributes and type aliases), once the tree for the object's package has been fully constructed. There are also specific **load events** for each object kind: -- [`on_module`][griffe.Extension.on_module]: The "on module" event is triggered on modules. -- [`on_class`][griffe.Extension.on_class]: The "on class" event is triggered on classes. -- [`on_function`][griffe.Extension.on_function]: The "on function" event is triggered on functions. -- [`on_attribute`][griffe.Extension.on_attribute]: The "on attribute" event is triggered on attributes. -- [`on_type_alias`][griffe.Extension.on_type_alias]: The "on type alias" event is triggered on type aliases. -- [`on_alias`][griffe.Extension.on_alias]: The "on alias" event is triggered on aliases (imported/inherited objects). -- [`on_package`][griffe.Extension.on_package]: The "on package" event is triggered on top-level modules (packages) only. +- [`on_module`][griffelib.Extension.on_module]: The "on module" event is triggered on modules. +- [`on_class`][griffelib.Extension.on_class]: The "on class" event is triggered on classes. +- [`on_function`][griffelib.Extension.on_function]: The "on function" event is triggered on functions. +- [`on_attribute`][griffelib.Extension.on_attribute]: The "on attribute" event is triggered on attributes. +- [`on_type_alias`][griffelib.Extension.on_type_alias]: The "on type alias" event is triggered on type aliases. +- [`on_alias`][griffelib.Extension.on_alias]: The "on alias" event is triggered on aliases (imported/inherited objects). +- [`on_package`][griffelib.Extension.on_package]: The "on package" event is triggered on top-level modules (packages) only. #### Analysis events @@ -216,29 +216,29 @@ There are also specific **load events** for each object kind: There are 3 generic **analysis events**: -- [`on_node`][griffe.Extension.on_node]: The "on node" events are triggered when the agent (visitor or inspector) starts handling a node in the tree (AST or object tree). -- [`on_instance`][griffe.Extension.on_instance]: The "on instance" events are triggered when the agent just created an instance of [Module][griffe.Module], [Class][griffe.Class], [Function][griffe.Function], [Attribute][griffe.Attribute], or [Type Alias][griffe.TypeAlias], and added it as a member of its parent. The "on instance" event is **not** triggered when an [Alias][griffe.Alias] is created. -- [`on_members`][griffe.Extension.on_members]: The "on members" events are triggered when the agent just finished handling all the members of an object. Functions, attributes and type aliases do not have members, so there are no "on members" events for these kinds. +- [`on_node`][griffelib.Extension.on_node]: The "on node" events are triggered when the agent (visitor or inspector) starts handling a node in the tree (AST or object tree). +- [`on_instance`][griffelib.Extension.on_instance]: The "on instance" events are triggered when the agent just created an instance of [Module][griffelib.Module], [Class][griffelib.Class], [Function][griffelib.Function], [Attribute][griffelib.Attribute], or [Type Alias][griffelib.TypeAlias], and added it as a member of its parent. The "on instance" event is **not** triggered when an [Alias][griffelib.Alias] is created. +- [`on_members`][griffelib.Extension.on_members]: The "on members" events are triggered when the agent just finished handling all the members of an object. Functions, attributes and type aliases do not have members, so there are no "on members" events for these kinds. There are also specific **analysis events** for each object kind: -- [`on_module_node`][griffe.Extension.on_module_node] -- [`on_module_instance`][griffe.Extension.on_module_instance] -- [`on_module_members`][griffe.Extension.on_module_members] -- [`on_class_node`][griffe.Extension.on_class_node] -- [`on_class_instance`][griffe.Extension.on_class_instance] -- [`on_class_members`][griffe.Extension.on_class_members] -- [`on_function_node`][griffe.Extension.on_function_node] -- [`on_function_instance`][griffe.Extension.on_function_instance] -- [`on_attribute_node`][griffe.Extension.on_attribute_node] -- [`on_attribute_instance`][griffe.Extension.on_attribute_instance] -- [`on_type_alias_node`][griffe.Extension.on_type_alias_node] -- [`on_type_alias_instance`][griffe.Extension.on_type_alias_instance] -- [`on_alias_instance`][griffe.Extension.on_alias_instance] +- [`on_module_node`][griffelib.Extension.on_module_node] +- [`on_module_instance`][griffelib.Extension.on_module_instance] +- [`on_module_members`][griffelib.Extension.on_module_members] +- [`on_class_node`][griffelib.Extension.on_class_node] +- [`on_class_instance`][griffelib.Extension.on_class_instance] +- [`on_class_members`][griffelib.Extension.on_class_members] +- [`on_function_node`][griffelib.Extension.on_function_node] +- [`on_function_instance`][griffelib.Extension.on_function_instance] +- [`on_attribute_node`][griffelib.Extension.on_attribute_node] +- [`on_attribute_instance`][griffelib.Extension.on_attribute_instance] +- [`on_type_alias_node`][griffelib.Extension.on_type_alias_node] +- [`on_type_alias_instance`][griffelib.Extension.on_type_alias_instance] +- [`on_alias_instance`][griffelib.Extension.on_alias_instance] #### Extensions and hooks -**Extensions** are classes that inherit from [Griffe's Extension base class][griffe.Extension] and define some hooks as methods: +**Extensions** are classes that inherit from [Griffe's Extension base class][griffelib.Extension] and define some hooks as methods: ```python import griffe @@ -255,7 +255,7 @@ class MyExtension(griffe.Extension): """Do something with `obj`.""" ``` -Hooks are always defined as methods of a class inheriting from [Extension][griffe.Extension], never as standalone functions. IDEs should autocomplete the signature when you start typing `def` followed by a hook name. +Hooks are always defined as methods of a class inheriting from [Extension][griffelib.Extension], never as standalone functions. IDEs should autocomplete the signature when you start typing `def` followed by a hook name. Since hooks are declared in a class, feel free to also declare state variables (or any other variable) in the `__init__` method: @@ -307,10 +307,10 @@ class MyExtension(griffe.Extension): Extensions provide basic functionality to help you visit trees during analysis of the code: -- [`visit`][griffe.Extension.visit]: call `self.visit(node)` to start visiting an abstract syntax tree. -- [`generic_visit`][griffe.Extension.generic_visit]: call `self.generic_visit(node)` to visit each subnode of a given node. -- [`inspect`][griffe.Extension.inspect]: call `self.inspect(node)` to start visiting an object tree. Nodes contain references to the runtime objects, see [`ObjectNode`][griffe.ObjectNode]. -- [`generic_inspect`][griffe.Extension.generic_inspect]: call `self.generic_inspect(node)` to visit each subnode of a given node. +- [`visit`][griffelib.Extension.visit]: call `self.visit(node)` to start visiting an abstract syntax tree. +- [`generic_visit`][griffelib.Extension.generic_visit]: call `self.generic_visit(node)` to visit each subnode of a given node. +- [`inspect`][griffelib.Extension.inspect]: call `self.inspect(node)` to start visiting an object tree. Nodes contain references to the runtime objects, see [`ObjectNode`][griffelib.ObjectNode]. +- [`generic_inspect`][griffelib.Extension.generic_inspect]: call `self.generic_inspect(node)` to visit each subnode of a given node. Calling `self.visit(node)` or `self.inspect(node)` will do nothing unless you actually implement methods that handle specific types of nodes: @@ -333,7 +333,7 @@ Calling `self.visit(node)` or `self.inspect(node)` will do nothing unless you ac See the [list of existing AST classes](#ast-nodes) to learn what method you can implement. -- for object trees, methods must be named `inspect_`, where `` is replaced with the string value of the node's kind. The different kinds are listed in the [`ObjectKind`][griffe.ObjectKind] enumeration. For example, to allow inspecting coroutine nodes, you must implement the `inspect_coroutine` method: +- for object trees, methods must be named `inspect_`, where `` is replaced with the string value of the node's kind. The different kinds are listed in the [`ObjectKind`][griffelib.ObjectKind] enumeration. For example, to allow inspecting coroutine nodes, you must implement the `inspect_coroutine` method: ```python from griffe import Extension, ObjectNode @@ -349,7 +349,7 @@ Calling `self.visit(node)` or `self.inspect(node)` will do nothing unless you ac ### Triggering other extensions -If your extension creates new objects, you might want to trigger the other enabled extensions on these object instances. To do this you can use [`agent.extensions.call`][griffe.Extensions.call]: +If your extension creates new objects, you might want to trigger the other enabled extensions on these object instances. To do this you can use [`agent.extensions.call`][griffelib.Extensions.call]: ```python import ast diff --git a/docs/guide/users/how-to/parse-docstrings.md b/docs/guide/users/how-to/parse-docstrings.md index fef3d12ee..70ebb6c05 100644 --- a/docs/guide/users/how-to/parse-docstrings.md +++ b/docs/guide/users/how-to/parse-docstrings.md @@ -1,6 +1,6 @@ # Using Griffe as a docstring-parsing library -You can use Griffe to parse arbitrary docstrings. You don't have to load anything through the Griffe loader. You just need to import the [`Docstring`][griffe.Docstring] class. Then you can build a `Docstring` instance and call its `parse` method, choosing the parsing-style to use: +You can use Griffe to parse arbitrary docstrings. You don't have to load anything through the Griffe loader. You just need to import the [`Docstring`][griffelib.Docstring] class. Then you can build a `Docstring` instance and call its `parse` method, choosing the parsing-style to use: ```python from griffe import Docstring diff --git a/docs/guide/users/how-to/selectively-inspect.md b/docs/guide/users/how-to/selectively-inspect.md index 87be96210..f93e6a1c5 100644 --- a/docs/guide/users/how-to/selectively-inspect.md +++ b/docs/guide/users/how-to/selectively-inspect.md @@ -63,7 +63,7 @@ class InspectSpecificObjects(griffe.Extension): ... ``` -Check out the [available hooks][griffe.Extension] to see if there more appropriate hooks for your needs. +Check out the [available hooks][griffelib.Extension] to see if there more appropriate hooks for your needs. Lets now use our configuration option to decide whether to do something or skip: diff --git a/docs/guide/users/how-to/support-decorators.md b/docs/guide/users/how-to/support-decorators.md index b0fe8da5c..a68b98bc5 100644 --- a/docs/guide/users/how-to/support-decorators.md +++ b/docs/guide/users/how-to/support-decorators.md @@ -28,7 +28,7 @@ class MyDecorator(griffe.Extension): """An extension to suport my decorator.""" ``` -Now we can declare the [`on_instance`][griffe.Extension.on_instance] hook, which receives any kind of Griffe object ([`Module`][griffe.Module], [`Class`][griffe.Class], [`Function`][griffe.Function], [`Attribute`][griffe.Attribute], [`TypeAlias`][griffe.TypeAlias]), or we could use a kind-specific hook such as [`on_module_instance`][griffe.Extension.on_module_instance], [`on_class_instance`][griffe.Extension.on_class_instance], [`on_function_instance`][griffe.Extension.on_function_instance], [`on_attribute_instance`][griffe.Extension.on_attribute_instance] and [`on_type_alias_instance`][griffe.Extension.on_type_alias_instance]. For example, if you know your decorator is only ever used on class declarations, it would make sense to use `on_class_instance`. +Now we can declare the [`on_instance`][griffelib.Extension.on_instance] hook, which receives any kind of Griffe object ([`Module`][griffelib.Module], [`Class`][griffelib.Class], [`Function`][griffelib.Function], [`Attribute`][griffelib.Attribute], [`TypeAlias`][griffelib.TypeAlias]), or we could use a kind-specific hook such as [`on_module_instance`][griffelib.Extension.on_module_instance], [`on_class_instance`][griffelib.Extension.on_class_instance], [`on_function_instance`][griffelib.Extension.on_function_instance], [`on_attribute_instance`][griffelib.Extension.on_attribute_instance] and [`on_type_alias_instance`][griffelib.Extension.on_type_alias_instance]. For example, if you know your decorator is only ever used on class declarations, it would make sense to use `on_class_instance`. For the example, lets use the `on_function_instance` hook, which receives `Function` instances. @@ -58,4 +58,4 @@ class MyDecorator(griffe.Extension): ... # Update the function attributes. ``` -Now all that is left to do is to actually write the code that updates the function according to what the decorator is doing. We could update the function's docstring, or its return type, or its parameters: it all depends on your decorator and what it does to the objects it decorates. Check out the [API reference for function objects][griffe.Function] to see what data this object stores. +Now all that is left to do is to actually write the code that updates the function according to what the decorator is doing. We could update the function's docstring, or its return type, or its parameters: it all depends on your decorator and what it does to the objects it decorates. Check out the [API reference for function objects][griffelib.Function] to see what data this object stores. diff --git a/docs/guide/users/loading.md b/docs/guide/users/loading.md index 620917803..d658a6671 100644 --- a/docs/guide/users/loading.md +++ b/docs/guide/users/loading.md @@ -4,7 +4,7 @@ Griffe can load API data from both source code (static analysis) and objects at ## The `load` function -The main interface to load API data is Griffe's [`load`][griffe.load] function: +The main interface to load API data is Griffe's [`load`][griffelib.load] function: ```python import griffe @@ -56,7 +56,7 @@ my_installed_package = griffe.load("my_package", try_relative_path=False) ## The `GriffeLoader` class -The [`load`][griffe.load] function is a shortcut for instantiating the [`GriffeLoader`][griffe.GriffeLoader] class and calling its [`load`][griffe.GriffeLoader.load] method. Calling the [`load`][griffe.load] function multiple times will instantiate a new Griffe loader each time. If you care about efficiency, it is better to instantiate the loader yourself and use its `load` method: +The [`load`][griffelib.load] function is a shortcut for instantiating the [`GriffeLoader`][griffelib.GriffeLoader] class and calling its [`load`][griffelib.GriffeLoader.load] method. Calling the [`load`][griffelib.load] function multiple times will instantiate a new Griffe loader each time. If you care about efficiency, it is better to instantiate the loader yourself and use its `load` method: ```python import griffe @@ -72,7 +72,7 @@ Reusing the same loader will also help resolving aliases across different packag ## Search paths -To specify in which directories Griffe should search for packages and modules, you can use the `search_paths` parameter on both the [`load` function][griffe.load] and the [`GriffeLoader` class][griffe.GriffeLoader]. +To specify in which directories Griffe should search for packages and modules, you can use the `search_paths` parameter on both the [`load` function][griffelib.load] and the [`GriffeLoader` class][griffelib.GriffeLoader]. === "`load`" ```python @@ -138,7 +138,7 @@ griffe.load("itertools", allow_inspection=False) > > The name "alias" comes from the fact that imported objects can be aliased under a different name: `from X import A as B`. In the case of inherited members, this doesn't really apply, but we reuse the concept for conciseness. > -> An [`Alias`][griffe.Alias] instance is therefore a pointer to another object. It has its own name, parent, line numbers, and stores the path to the target object. Thanks to this path, we can access the actual target object and all its metadata, such as name, parent, line numbers, docstring, etc.. Obtaining a reference to the target object is what we call "alias resolution". +> An [`Alias`][griffelib.Alias] instance is therefore a pointer to another object. It has its own name, parent, line numbers, and stores the path to the target object. Thanks to this path, we can access the actual target object and all its metadata, such as name, parent, line numbers, docstring, etc.. Obtaining a reference to the target object is what we call "alias resolution". > > **To summarize, alias resolution is a post-process task that resolves imports after loading everything.** @@ -235,7 +235,7 @@ Traceback (most recent call last): griffe._internal.exceptions.AliasResolutionError: Could not resolve alias package2.X pointing at package1.X (in package2/__init__.py:1) ``` -As you can see in the interpreter session above, Griffe did not resolve the `X` alias. When we tried to access its target object anyway, it failed with a `KeyError`, which was raised again as an [`AliasResolutionError`][griffe.AliasResolutionError]. +As you can see in the interpreter session above, Griffe did not resolve the `X` alias. When we tried to access its target object anyway, it failed with a `KeyError`, which was raised again as an [`AliasResolutionError`][griffelib.AliasResolutionError]. Lets try again, but this time by loading both packages. @@ -257,15 +257,15 @@ The same exception again? What happened here? We loaded both packages, but Griff If you look closely at the first exception traceback, you will see that Griffe searched the target path in `self.modules_collection`. So what is this modules collection? -Each instance of [`GriffeLoader`][griffe.GriffeLoader] holds a reference to an instance of [`ModulesCollection`][griffe.ModulesCollection]. If you don't create such a collection manually to pass it to the loader, it will instantiate one itself. All objects loaded with this loader are added to this very modules collection, and gain a reference to it. +Each instance of [`GriffeLoader`][griffelib.GriffeLoader] holds a reference to an instance of [`ModulesCollection`][griffelib.ModulesCollection]. If you don't create such a collection manually to pass it to the loader, it will instantiate one itself. All objects loaded with this loader are added to this very modules collection, and gain a reference to it. -Since the [`load` function][griffe.load] is just a shortcut for creating a loader and calling its [`load` method][griffe.GriffeLoader.load], when we called `griffe.load(...)` twice, it actually created two distinct collections of modules. When Griffe tried to resolve aliases of `package2`, it looked for `package1` in `package2`'s collection, and couldn't find it. Indeed, `package1` was in another modules collection. +Since the [`load` function][griffelib.load] is just a shortcut for creating a loader and calling its [`load` method][griffelib.GriffeLoader.load], when we called `griffe.load(...)` twice, it actually created two distinct collections of modules. When Griffe tried to resolve aliases of `package2`, it looked for `package1` in `package2`'s collection, and couldn't find it. Indeed, `package1` was in another modules collection. Therefore, to resolve aliases *across different packages*, these packages must be loaded within the same modules collection. In order to do that, you have a few options: - instantiate a single loader, and use it to load both packages -- create your own modules collection, and pass it to the [`load` function][griffe.load] each time you call it -- create your own modules collection, and pass it to the different instances of [`GriffeLoader`][griffe.GriffeLoader] you create +- create your own modules collection, and pass it to the [`load` function][griffelib.load] each time you call it +- create your own modules collection, and pass it to the different instances of [`GriffeLoader`][griffelib.GriffeLoader] you create === "Same loader" ```pycon @@ -334,7 +334,7 @@ By default, Griffe runs some Git commands to find the following information abou - what service it corresponds to (GitHub, etc.) - the current commit hash -It then assigns this information to each package it loads, in the [`git_info`][griffe.Object.git_info] attribute. This attribute can be reassigned on any object, if necessary. Each object who has it set to `None` will look into its parents. +It then assigns this information to each package it loads, in the [`git_info`][griffelib.Object.git_info] attribute. This attribute can be reassigned on any object, if necessary. Each object who has it set to `None` will look into its parents. In the following cases, the information will not be set: @@ -343,15 +343,15 @@ In the following cases, the information will not be set: - Griffe cannot identify a known, supported service from the remote URL - any Git command failed -Griffe supports the services listed in the [`KnownGitService`][griffe.KnownGitService] symbol. Please open a feature request if you would like to add support for other services. +Griffe supports the services listed in the [`KnownGitService`][griffelib.KnownGitService] symbol. Please open a feature request if you would like to add support for other services. -Thanks to this source information, Griffe can then compute [source links][griffe.Object.source_link] for each objects, by combining the information with the object's filepath and line numbers. +Thanks to this source information, Griffe can then compute [source links][griffelib.Object.source_link] for each objects, by combining the information with the object's filepath and line numbers. You can globally change how Griffe obtains the source information with the following environment variables: - `GRIFFE_GIT_REMOTE_URL`: It is the repository remote URL, as an HTTPS link that readers of your documentation can access to see the repository online, on the service it is hosted on. Example: `GRIFFE_GIT_REMOTE_URL=https://app.radicle.at/nodes/seed.radicle.at/rad:z4M5XTPDD4Wh1sm8iPCenF85J3z8Z`. - `GRIFFE_GIT_REMOTE`: You can also let Griffe obtain the remote URL by getting it from the Git local configuration. The Git remote defaults to `origin`. This environment variable lets you change it to something else. Example: `GRIFFE_GIT_REMOTE=upstream`. -- `GRIFFE_GIT_SERVICE`: Griffe infers the service by looking at the remote URL. If the remote URL contains a [known service name][griffe.KnownGitService], Griffe will use it as service. You can otherwise explicitly set the service using this environment variable. Example: `GRIFFE_GIT_SERVICE=codeberg`. +- `GRIFFE_GIT_SERVICE`: Griffe infers the service by looking at the remote URL. If the remote URL contains a [known service name][griffelib.KnownGitService], Griffe will use it as service. You can otherwise explicitly set the service using this environment variable. Example: `GRIFFE_GIT_SERVICE=codeberg`. - `GRIFFE_GIT_COMMIT_HASH`: Griffe gets the commit hash by running a Git command. If you prefer using another commit hash, you can set it using this environment variable. Example: `GRIFFE_GIT_COMMIT_HASH=77f928aeab857cb45564462a4f849c2df2cca99a`. For more complex cases, see [How to programmatically set the correct Git information or source link on objects](how-to/set-git-info.md). diff --git a/docs/guide/users/navigating.md b/docs/guide/users/navigating.md index 75a1a0ab3..9cb78fa0f 100644 --- a/docs/guide/users/navigating.md +++ b/docs/guide/users/navigating.md @@ -2,12 +2,12 @@ Griffe loads API data into data models. These models provide various attributes and methods to access or update specific fields. The different models are: -- [`Module`][griffe.Module], representing Python modules; -- [`Class`][griffe.Class], representing Python classes; -- [`Function`][griffe.Function], representing Python functions and class methods; -- [`Attribute`][griffe.Attribute], representing object attributes that weren't identified as modules, classes or functions; -- [`Type Alias`][griffe.TypeAlias], representing Python type aliases; -- [`Alias`][griffe.Alias], representing indirections such as imported objects or class members inherited from parent classes. +- [`Module`][griffelib.Module], representing Python modules; +- [`Class`][griffelib.Class], representing Python classes; +- [`Function`][griffelib.Function], representing Python functions and class methods; +- [`Attribute`][griffelib.Attribute], representing object attributes that weren't identified as modules, classes or functions; +- [`Type Alias`][griffelib.TypeAlias], representing Python type aliases; +- [`Alias`][griffelib.Alias], representing indirections such as imported objects or class members inherited from parent classes. When [loading an object](loading.md), Griffe will give you back an instance of one of these models. A few examples: @@ -31,13 +31,13 @@ However deep the object is, Griffe loads the entire package. It means that in al ## Moving up: parents -Each object holds a reference to its [`parent`][griffe.Object.parent] (except for the top-level module, for which the parent is `None`). Shortcuts are provided to climb up directly to the parent [`module`][griffe.Object.module], or the top-level [`package`][griffe.Object.package]. As we have seen in the [Loading chapter](loading.md), Griffe stores all loaded modules in a modules collection; this collection can be accessed too, through the [`modules_collection`][griffe.Object.modules_collection] attribute. +Each object holds a reference to its [`parent`][griffelib.Object.parent] (except for the top-level module, for which the parent is `None`). Shortcuts are provided to climb up directly to the parent [`module`][griffelib.Object.module], or the top-level [`package`][griffelib.Object.package]. As we have seen in the [Loading chapter](loading.md), Griffe stores all loaded modules in a modules collection; this collection can be accessed too, through the [`modules_collection`][griffelib.Object.modules_collection] attribute. ## Moving down: members To access an object's members, there are a few options: -- Access to regular members through the [`members`][griffe.Object.members] attribute, which is a dictionary. The keys are member names, the values are Griffe models. +- Access to regular members through the [`members`][griffelib.Object.members] attribute, which is a dictionary. The keys are member names, the values are Griffe models. ```pycon >>> import griffe @@ -48,7 +48,7 @@ To access an object's members, there are a few options: Class('Markdown', 46, 451) ``` -- Access to both regular and inherited members through the [`all_members`][griffe.Object.all_members] attribute, which is a dictionary again. See [Inherited members](#inherited-members). +- Access to both regular and inherited members through the [`all_members`][griffelib.Object.all_members] attribute, which is a dictionary again. See [Inherited members](#inherited-members). - Convenient dictionary-like item access, thanks to the subscript syntax `[]`. With this syntax, you will not only be able to chain accesses, but also merge them into a single access by using dot-separated paths to objects: @@ -74,7 +74,7 @@ To access an object's members, there are a few options: Class('Markdown', 46, 451) ``` -- Less convenient, but safer access to members while the object tree is being built (while a package is still being loaded), using the [`get_member()`][griffe.GetMembersMixin.get_member] method. +- Less convenient, but safer access to members while the object tree is being built (while a package is still being loaded), using the [`get_member()`][griffelib.GetMembersMixin.get_member] method. ```pycon >>> import griffe @@ -85,7 +85,7 @@ To access an object's members, there are a few options: In particular, Griffe extensions should always use `get_member` instead of the subscript syntax `[]`. The `get_member` method only looks into regular members, while the subscript syntax looks into inherited members too (for classes), which cannot be correctly computed until a package is fully loaded (which is generally not the case when an extension is running). -- In addition to this, models provide the [`attributes`][griffe.Object.attributes], [`functions`][griffe.Object.functions], [`classes`][griffe.Object.classes], [`type_aliases`][griffe.Object.type_aliases] or [`modules`][griffe.Object.modules] attributes, which return only members of the corresponding kind. These attributes are computed dynamically each time (they are Python properties). +- In addition to this, models provide the [`attributes`][griffelib.Object.attributes], [`functions`][griffelib.Object.functions], [`classes`][griffelib.Object.classes], [`type_aliases`][griffelib.Object.type_aliases] or [`modules`][griffelib.Object.modules] attributes, which return only members of the corresponding kind. These attributes are computed dynamically each time (they are Python properties). The same way members are accessed, they can also be set: @@ -97,15 +97,15 @@ The same way members are accessed, they can also be set: - Dictionary-like item deletion: `del markdown["thing"]`, also supporting dotted-paths and string tuples. This will delete only regular members: inherited members (classes only) are re-computed everytime they are accessed. - Safer method for extensions: `markdown.del_member("thing")`, also supporting dotted-paths and string tuples. -- Regular member deletion: `del markdown.members["thing"]`. **This is not recommended, as the [`aliases`][griffe.Object.aliases] attribute of other objects in the tree will not be automatically updated.** +- Regular member deletion: `del markdown.members["thing"]`. **This is not recommended, as the [`aliases`][griffelib.Object.aliases] attribute of other objects in the tree will not be automatically updated.** ### Inherited members Griffe supports class inheritance, both when visiting and inspecting modules. -To access members of a class that are inherited from base classes, use the [`inherited_members`][griffe.Object.inherited_members] attribute. Everytime you access inherited members, the base classes of the given class will be resolved, then the MRO (Method Resolution Order) will be computed for these base classes, and a dictionary of inherited members will be built. Make sure to store the result in a variable to avoid re-computing it everytime (you are responsible for the caching part). Also make sure to only access `inherited_members` once everything is loaded by Griffe, to avoid computing things too early. Don't try to access inherited members in extensions, while visiting or inspecting modules. +To access members of a class that are inherited from base classes, use the [`inherited_members`][griffelib.Object.inherited_members] attribute. Everytime you access inherited members, the base classes of the given class will be resolved, then the MRO (Method Resolution Order) will be computed for these base classes, and a dictionary of inherited members will be built. Make sure to store the result in a variable to avoid re-computing it everytime (you are responsible for the caching part). Also make sure to only access `inherited_members` once everything is loaded by Griffe, to avoid computing things too early. Don't try to access inherited members in extensions, while visiting or inspecting modules. -Inherited members are aliases that point at the corresponding members in parent classes. These aliases will have their [`inherited`][griffe.Alias.inherited] attribute set to true. +Inherited members are aliases that point at the corresponding members in parent classes. These aliases will have their [`inherited`][griffelib.Alias.inherited] attribute set to true. **Important:** only classes from already loaded packages will be used when computing inherited members. This gives users control over how deep into inheritance to go, by pre-loading packages from which you want to inherit members. For example, if `package_c.ClassC` inherits from `package_b.ClassB`, itself inheriting from `package_a.ClassA`, and you want to load `ClassB` members only: @@ -120,9 +120,9 @@ loader.load("package_c") If a base class cannot be resolved during computation of inherited members, Griffe logs a DEBUG message. -If you want to access all members at once (both declared and inherited), use the [`all_members`][griffe.Object.all_members] attribute. If you want to access only declared members, use the [`members`][griffe.Object] attribute. +If you want to access all members at once (both declared and inherited), use the [`all_members`][griffelib.Object.all_members] attribute. If you want to access only declared members, use the [`members`][griffelib.Object] attribute. -Accessing the [`attributes`][griffe.Object.attributes], [`functions`][griffe.Object.functions], [`classes`][griffe.Object.classes], [`type_aliases`][griffe.Object.type_aliases] or [`modules`][griffe.Object.modules] attributes will trigger inheritance computation, so make sure to only access them once everything is loaded by Griffe. Don't try to access inherited members in extensions, while visiting or inspecting modules. +Accessing the [`attributes`][griffelib.Object.attributes], [`functions`][griffelib.Object.functions], [`classes`][griffelib.Object.classes], [`type_aliases`][griffelib.Object.type_aliases] or [`modules`][griffelib.Object.modules] attributes will trigger inheritance computation, so make sure to only access them once everything is loaded by Griffe. Don't try to access inherited members in extensions, while visiting or inspecting modules. #### Limitations @@ -174,18 +174,18 @@ We will try to lift these limitations in the future. ## Aliases -Aliases represent indirections, such as objects imported from elsewhere, attributes, or methods inherited from parent classes. They are pointers to the object they represent. The path of the object they represent is stored in their [`target_path`][griffe.Alias.target_path] attribute. Once they are resolved, the target object can be accessed through their [`target`][griffe.Alias.target] attribute. +Aliases represent indirections, such as objects imported from elsewhere, attributes, or methods inherited from parent classes. They are pointers to the object they represent. The path of the object they represent is stored in their [`target_path`][griffelib.Alias.target_path] attribute. Once they are resolved, the target object can be accessed through their [`target`][griffelib.Alias.target] attribute. -Aliases can be found in objects' members. Each object can also access its own aliases (the aliases pointing at it) through its [`aliases`][griffe.Object.aliases] attribute. This attribute is a dictionary whose keys are the aliases paths and values are the aliases themselves. +Aliases can be found in objects' members. Each object can also access its own aliases (the aliases pointing at it) through its [`aliases`][griffelib.Object.aliases] attribute. This attribute is a dictionary whose keys are the aliases paths and values are the aliases themselves. Most of the time, aliases simply act as proxies to their target objects. For example, accessing the `docstring` of an alias will simply return the docstring of the object it targets. -Accessing fields on aliases will trigger their resolution. If they are already resolved (their `target` attribute is set to the target object), the field is returned. If they are not resolved, their target path will be looked up in the modules collection, and if it is found, the object at this location will be assigned to the alias' `target` attribute. If it isn't found, an [`AliasResolutionError`][griffe.AliasResolutionError] exception will be raised. +Accessing fields on aliases will trigger their resolution. If they are already resolved (their `target` attribute is set to the target object), the field is returned. If they are not resolved, their target path will be looked up in the modules collection, and if it is found, the object at this location will be assigned to the alias' `target` attribute. If it isn't found, an [`AliasResolutionError`][griffelib.AliasResolutionError] exception will be raised. Since merely accessing an alias field can raise an exception, it is often useful to check if an object is an alias before accessing its fields. There are multiple ways to check if an object is an alias: -- using the `is_alias` boolean ([`Object.is_alias`][griffe.Object.is_alias], [`Alias.is_alias`][griffe.Alias.is_alias]), which won't trigger resolution -- using `isinstance` to check if the object is an instance of [`Alias`][griffe.Alias] +- using the `is_alias` boolean ([`Object.is_alias`][griffelib.Object.is_alias], [`Alias.is_alias`][griffelib.Alias.is_alias]), which won't trigger resolution +- using `isinstance` to check if the object is an instance of [`Alias`][griffelib.Alias] ```pycon >>> import griffe @@ -196,7 +196,7 @@ True True ``` -The [`kind`][griffe.Alias.kind] of an alias will only return [`ALIAS`][griffe.Kind.ALIAS] if the alias is not resolved and cannot be resolved within the current modules collection. +The [`kind`][griffelib.Alias.kind] of an alias will only return [`ALIAS`][griffelib.Kind.ALIAS] if the alias is not resolved and cannot be resolved within the current modules collection. You can of course also catch any raised exception with a regular try/except block: @@ -207,13 +207,13 @@ except griffe.AliasResolutionError: pass ``` -To check if an alias is already resolved, you can use its [`resolved`][griffe.Alias.resolved] attribute. +To check if an alias is already resolved, you can use its [`resolved`][griffelib.Alias.resolved] attribute. ### Alias chains -Aliases can be chained. For example, if module `a` imports `X` from module `b`, which itself imports `X` from module `c`, then `a.X` is an alias to `b.X` which is an alias to `c.X`: `a.X` -> `b.X` -> `c.X`. To access the final target directly, you can use the [`final_target`][griffe.Alias.final_target] attribute. Most alias properties that act like proxies actually fetch the final target rather than the next one to return the final field. +Aliases can be chained. For example, if module `a` imports `X` from module `b`, which itself imports `X` from module `c`, then `a.X` is an alias to `b.X` which is an alias to `c.X`: `a.X` -> `b.X` -> `c.X`. To access the final target directly, you can use the [`final_target`][griffelib.Alias.final_target] attribute. Most alias properties that act like proxies actually fetch the final target rather than the next one to return the final field. -Sometimes, when a package makes use of complicated imports (wildcard imports from parents and submodules), or when runtime objects are hard to inspect, it is possible to end up with a cyclic chain of aliases. You could for example end up with a chain like `a.X` -> `b.X` -> `c.X` -> `a.X`. In this case, the alias *cannot* be resolved, since the chain goes in a loop. Griffe will raise a [`CyclicAliasError`][griffe.CyclicAliasError] when trying to resolve such cyclic chains. +Sometimes, when a package makes use of complicated imports (wildcard imports from parents and submodules), or when runtime objects are hard to inspect, it is possible to end up with a cyclic chain of aliases. You could for example end up with a chain like `a.X` -> `b.X` -> `c.X` -> `a.X`. In this case, the alias *cannot* be resolved, since the chain goes in a loop. Griffe will raise a [`CyclicAliasError`][griffelib.CyclicAliasError] when trying to resolve such cyclic chains. Aliases chains are never partially resolved: either they are resolved down to their final target, or none of their links are resolved. @@ -221,9 +221,9 @@ Aliases chains are never partially resolved: either they are resolved down to th The kind of an object (module, class, function, attribute, type alias or alias) can be obtained in several ways. -- With the [`kind`][griffe.Object.kind] attribute and the [`Kind`][griffe.Kind] enumeration: `obj.kind is Kind.MODULE`. +- With the [`kind`][griffelib.Object.kind] attribute and the [`Kind`][griffelib.Kind] enumeration: `obj.kind is Kind.MODULE`. -- With the [`is_kind()`][griffe.Object.is_kind] method: +- With the [`is_kind()`][griffelib.Object.is_kind] method: - `obj.is_kind(Kind.MODULE)` - `obj.is_kind("class")` @@ -231,21 +231,21 @@ The kind of an object (module, class, function, attribute, type alias or alias) When given a set of kinds, the method returns true if the object is of one of the given kinds. -- With the [`is_module`][griffe.Object.is_module], [`is_class`][griffe.Object.is_class], [`is_function`][griffe.Object.is_function], [`is_attribute`][griffe.Object.is_attribute], [`is_type_alias`][griffe.Object.is_type_alias], and [`is_alias`][griffe.Object.is_alias] attributes. +- With the [`is_module`][griffelib.Object.is_module], [`is_class`][griffelib.Object.is_class], [`is_function`][griffelib.Object.is_function], [`is_attribute`][griffelib.Object.is_attribute], [`is_type_alias`][griffelib.Object.is_type_alias], and [`is_alias`][griffelib.Object.is_alias] attributes. Additionally, it is possible to check if an object is a sub-kind of module, with the following attributes: -- [`is_init_module`][griffe.Object.is_init_module], for `__init__.py` modules -- [`is_package`][griffe.Object.is_package], for top-level packages -- [`is_subpackage`][griffe.Object.is_subpackage], for non-top-level packages -- [`is_namespace_package`][griffe.Object.is_namespace_package], for top-level [namespace packages](https://packaging.python.org/en/latest/guides/packaging-namespace-packages/) -- [`is_namespace_subpackage`][griffe.Object.is_namespace_subpackage], for non-top-level namespace packages +- [`is_init_module`][griffelib.Object.is_init_module], for `__init__.py` modules +- [`is_package`][griffelib.Object.is_package], for top-level packages +- [`is_subpackage`][griffelib.Object.is_subpackage], for non-top-level packages +- [`is_namespace_package`][griffelib.Object.is_namespace_package], for top-level [namespace packages](https://packaging.python.org/en/latest/guides/packaging-namespace-packages/) +- [`is_namespace_subpackage`][griffelib.Object.is_namespace_subpackage], for non-top-level namespace packages -Finally, additional [`labels`][griffe.Object.labels] are attached to objects to further specify their kind. The [`has_labels()`][griffe.Object.has_labels] method can be used to check if an object has several specific labels. +Finally, additional [`labels`][griffelib.Object.labels] are attached to objects to further specify their kind. The [`has_labels()`][griffelib.Object.has_labels] method can be used to check if an object has several specific labels. ## Object location -An object is identified by its [`path`][griffe.Object.path], which is its location in the object tree. The path is composed of all the parent names and the object name, separated by dots, for example `mod.Class.meth`. This `path` is the [`canonical_path`][griffe.Object.canonical_path] on regular objects. For aliases however, the `path` is *where they are imported* while the canonical path is *where they come from*. Example: +An object is identified by its [`path`][griffelib.Object.path], which is its location in the object tree. The path is composed of all the parent names and the object name, separated by dots, for example `mod.Class.meth`. This `path` is the [`canonical_path`][griffelib.Object.canonical_path] on regular objects. For aliases however, the `path` is *where they are imported* while the canonical path is *where they come from*. Example: ```python # pkg1.py @@ -265,20 +265,20 @@ from pkg2 import A as B Information on the actual source code of objects is available through the following attributes: -- [`filepath`][griffe.Object.filepath], the absolute path to the module the object appears in, for example `~/project/src/pkg/mod.py` -- [`relative_filepath`][griffe.Object.relative_filepath], the relative path to the module, compared to the current working directory, for example `src/pkg/mod.py` -- [`relative_package_filepath`][griffe.Object.relative_package_filepath], the relative path to the module, compared to the parent of the top-level package, for example `pkg/mod.py` -- [`lineno`][griffe.Object.lineno] and [`endlineno`][griffe.Object.endlineno], the starting and ending line numbers of the object in the source -- [`lines`][griffe.Object.lines], the lines of code defining the object (or importing the alias) -- [`source`][griffe.Object.source], the source lines concatenated as a single multiline string +- [`filepath`][griffelib.Object.filepath], the absolute path to the module the object appears in, for example `~/project/src/pkg/mod.py` +- [`relative_filepath`][griffelib.Object.relative_filepath], the relative path to the module, compared to the current working directory, for example `src/pkg/mod.py` +- [`relative_package_filepath`][griffelib.Object.relative_package_filepath], the relative path to the module, compared to the parent of the top-level package, for example `pkg/mod.py` +- [`lineno`][griffelib.Object.lineno] and [`endlineno`][griffelib.Object.endlineno], the starting and ending line numbers of the object in the source +- [`lines`][griffelib.Object.lines], the lines of code defining the object (or importing the alias) +- [`source`][griffelib.Object.source], the source lines concatenated as a single multiline string -Each object holds a reference to a [`lines_collection`][griffe.Object.lines_collection]. Similar to the modules collection, this lines collection is a dictionary whose keys are module file-paths and values are their contents as list of lines. The lines collection is populated by the loader. +Each object holds a reference to a [`lines_collection`][griffelib.Object.lines_collection]. Similar to the modules collection, this lines collection is a dictionary whose keys are module file-paths and values are their contents as list of lines. The lines collection is populated by the loader. ## Object visibility Each object has fields that are related to their visibility within the API. -- [`is_public`][griffe.Object.is_public]: whether this object is public (destined to be consumed by your users). For module-level objects, Griffe considers that the object is public if: +- [`is_public`][griffelib.Object.is_public]: whether this object is public (destined to be consumed by your users). For module-level objects, Griffe considers that the object is public if: - it is listed in its parent module's `__all__` attribute - or if its parent module does not declare `__all__`, and the object doesn't have a private name, and the object is not imported from elsewhere @@ -312,36 +312,36 @@ Each object has fields that are related to their visibility within the API. ... ``` -- [`is_deprecated`][griffe.Object.is_deprecated]: whether this object is deprecated and shouldn't be used. +- [`is_deprecated`][griffelib.Object.is_deprecated]: whether this object is deprecated and shouldn't be used. -- [`is_special`][griffe.Object.is_special]: whether this object has a special name like `__special__` +- [`is_special`][griffelib.Object.is_special]: whether this object has a special name like `__special__` -- [`is_private`][griffe.Object.is_private]: whether this object has a private name like `_private` or `__private`, but not `__special__` +- [`is_private`][griffelib.Object.is_private]: whether this object has a private name like `_private` or `__private`, but not `__special__` -- [`is_class_private`][griffe.Object.is_class_private]: whether this object has a class-private name like `__private` and is a member of a class +- [`is_class_private`][griffelib.Object.is_class_private]: whether this object has a class-private name like `__private` and is a member of a class Since `is_private` only checks the name of the object, it is not mutually exclusive with `is_public`. It means an object can return true for both `is_public` and `is_private`. We invite Griffe users to mostly rely on `is_public` and `not is_public`. -It is possible to force `is_public` and `is_deprecated` to return true or false by setting the [`public`][griffe.Object.public] and [`deprecated`][griffe.Object.deprecated] fields respectively. These fields are typically set by extensions that support new ways of marking objects as public or deprecated. +It is possible to force `is_public` and `is_deprecated` to return true or false by setting the [`public`][griffelib.Object.public] and [`deprecated`][griffelib.Object.deprecated] fields respectively. These fields are typically set by extensions that support new ways of marking objects as public or deprecated. ## Imports/exports -Modules and classes populate their [`imports`][griffe.Object.imports] field with names that were imported from other modules. Similarly, modules populate their [`exports`][griffe.Object.exports] field with names that were exported by being listed into the module's `__all__` attribute. Each object then provides then [`is_imported`][griffe.Object.is_imported] and [`is_exported`][griffe.Object.is_exported] fields, which tell if an object was imported or exported respectively. Additionally, objects also provide an [`is_wildcard_exposed`][griffe.Object.is_wildcard_exposed] field that tells if an object is exposed to wildcard imports, i.e. will be imported when another module does `from this_module import *`. +Modules and classes populate their [`imports`][griffelib.Object.imports] field with names that were imported from other modules. Similarly, modules populate their [`exports`][griffelib.Object.exports] field with names that were exported by being listed into the module's `__all__` attribute. Each object then provides then [`is_imported`][griffelib.Object.is_imported] and [`is_exported`][griffelib.Object.is_exported] fields, which tell if an object was imported or exported respectively. Additionally, objects also provide an [`is_wildcard_exposed`][griffelib.Object.is_wildcard_exposed] field that tells if an object is exposed to wildcard imports, i.e. will be imported when another module does `from this_module import *`. ## Docstrings -Each object has an optional [`docstring`][griffe.Object.docstring] attached to it. To check whether it has one without comparing against `None`, the two following fields can be used: +Each object has an optional [`docstring`][griffelib.Object.docstring] attached to it. To check whether it has one without comparing against `None`, the two following fields can be used: -- [`has_docstring`][griffe.Object.has_docstring]: whether this object has a docstring (even empty) -- [`has_docstrings`][griffe.Object.has_docstrings]: same thing, but recursive; whether this object or any of its members has a docstring (even empty) +- [`has_docstring`][griffelib.Object.has_docstring]: whether this object has a docstring (even empty) +- [`has_docstrings`][griffelib.Object.has_docstrings]: same thing, but recursive; whether this object or any of its members has a docstring (even empty) -[Docstrings][griffe.Docstring] provide their cleaned-up [`value`][griffe.Docstring.value] (de-indented string, stripped from leading and trailing newlines), as well as their starting and ending line numbers with [`lineno`][griffe.Docstring.lineno] and [`endlineno`][griffe.Docstring.endlineno]. +[Docstrings][griffelib.Docstring] provide their cleaned-up [`value`][griffelib.Docstring.value] (de-indented string, stripped from leading and trailing newlines), as well as their starting and ending line numbers with [`lineno`][griffelib.Docstring.lineno] and [`endlineno`][griffelib.Docstring.endlineno]. Docstrings can be parsed against several [docstring-styles](../../reference/docstrings.md), which are micro-formats that allow documenting things such as parameters, returned values, raised exceptions, etc.. -When loading a package, it is possible to specify the docstring style to attach to every docstring (see the `docstring_parser` parameter of [`griffe.load`][griffe.load]). Accessing the [`parsed`][griffe.Docstring.parsed] field of a docstring will use this style to parse the docstring and return a list of [docstring sections][advanced-api-sections]. Each section has a `value` whose shape depends on the section kind. For example, parameter sections have a list of parameter representations as value, while a text section only has a string as value. +When loading a package, it is possible to specify the docstring style to attach to every docstring (see the `docstring_parser` parameter of [`griffe.load`][griffelib.load]). Accessing the [`parsed`][griffelib.Docstring.parsed] field of a docstring will use this style to parse the docstring and return a list of [docstring sections][advanced-api-sections]. Each section has a `value` whose shape depends on the section kind. For example, parameter sections have a list of parameter representations as value, while a text section only has a string as value. -After a package is loaded, it is still possible to change the style used for specific docstrings by either overriding their [`parser`][griffe.Docstring.parser] and [`parser_options`][griffe.Docstring.parser_options] attributes, or by calling their [`parse()`][griffe.Docstring.parse] method with a different style: +After a package is loaded, it is still possible to change the style used for specific docstrings by either overriding their [`parser`][griffelib.Docstring.parser] and [`parser_options`][griffelib.Docstring.parser_options] attributes, or by calling their [`parse()`][griffelib.Docstring.parse] method with a different style: ```pycon >>> import griffe @@ -352,7 +352,7 @@ After a package is loaded, it is still possible to change the style used for spe Do note, however, that the `parsed` attribute is cached, and won't be reset when overriding the `parser` or `parser_options` values. -Docstrings have a [`parent`][griffe.Docstring.parent] field too, that is a reference to their respective module, class, function, attribute or type alias. +Docstrings have a [`parent`][griffelib.Docstring.parent] field too, that is a reference to their respective module, class, function, attribute or type alias. ## Model-specific fields @@ -360,46 +360,46 @@ Models have most fields in common, but also have specific fields. ### Modules -- [`imports_future_annotations`][griffe.Module.imports_future_annotations]: Whether the module imports [future annotations](https://peps.python.org/pep-0563/), which changes the way we parse type annotations. -- [`overloads`][griffe.Module.overloads]: A dictionary to store overloads for module-level functions. +- [`imports_future_annotations`][griffelib.Module.imports_future_annotations]: Whether the module imports [future annotations](https://peps.python.org/pep-0563/), which changes the way we parse type annotations. +- [`overloads`][griffelib.Module.overloads]: A dictionary to store overloads for module-level functions. ### Classes -- [`bases`][griffe.Class.bases]: A list of class bases in the form of [expressions][griffe.Expr]. -- [`resolved_bases`][griffe.Class.resolved_bases]: A list of class bases, in the form of [Class][griffe.Class] objects. Only the bases that were loaded are returned, the others are discarded. -- [`mro()`][griffe.Class.mro]: A method to compute the Method Resolution Order in the form of a list of [Class][griffe.Class] objects. -- [`overloads`][griffe.Class.overloads]: A dictionary to store overloads for class-level methods. -- [`decorators`][griffe.Class.decorators]: The [decorators][griffe.Decorator] applied to the class. -- [`parameters`][griffe.Class.parameters]: The [parameters][griffe.Parameters] of the class' `__init__` method, if any. -- [`type_parameters`][griffe.Class.type_parameters]: The [type parameters][griffe.TypeParameters] of the class. +- [`bases`][griffelib.Class.bases]: A list of class bases in the form of [expressions][griffelib.Expr]. +- [`resolved_bases`][griffelib.Class.resolved_bases]: A list of class bases, in the form of [Class][griffelib.Class] objects. Only the bases that were loaded are returned, the others are discarded. +- [`mro()`][griffelib.Class.mro]: A method to compute the Method Resolution Order in the form of a list of [Class][griffelib.Class] objects. +- [`overloads`][griffelib.Class.overloads]: A dictionary to store overloads for class-level methods. +- [`decorators`][griffelib.Class.decorators]: The [decorators][griffelib.Decorator] applied to the class. +- [`parameters`][griffelib.Class.parameters]: The [parameters][griffelib.Parameters] of the class' `__init__` method, if any. +- [`type_parameters`][griffelib.Class.type_parameters]: The [type parameters][griffelib.TypeParameters] of the class. ### Functions -- [`decorators`][griffe.Function.decorators]: The [decorators][griffe.Decorator] applied to the function. -- [`overloads`][griffe.Function.overloads]: The overloaded signatures of the function. -- [`parameters`][griffe.Function.parameters]: The [parameters][griffe.Parameters] of the function. -- [`returns`][griffe.Function.returns]: The type annotation of the returned value, in the form of an [expression][griffe.Expr]. The `annotation` field can also be used, for compatibility with attributes. -- [`type_parameters`][griffe.Function.type_parameters]: The [type parameters][griffe.TypeParameters] of the function. +- [`decorators`][griffelib.Function.decorators]: The [decorators][griffelib.Decorator] applied to the function. +- [`overloads`][griffelib.Function.overloads]: The overloaded signatures of the function. +- [`parameters`][griffelib.Function.parameters]: The [parameters][griffelib.Parameters] of the function. +- [`returns`][griffelib.Function.returns]: The type annotation of the returned value, in the form of an [expression][griffelib.Expr]. The `annotation` field can also be used, for compatibility with attributes. +- [`type_parameters`][griffelib.Function.type_parameters]: The [type parameters][griffelib.TypeParameters] of the function. ### Attributes -- [`annotation`][griffe.Attribute.annotation]: The type annotation of the attribute, in the form of an [expression][griffe.Expr]. -- [`value`][griffe.Attribute.value]: The value of the attribute, in the form of an [expression][griffe.Expr]. -- [`deleter`][griffe.Attribute.deleter]: The property deleter. -- [`setter`][griffe.Attribute.setter]: The property setter. +- [`annotation`][griffelib.Attribute.annotation]: The type annotation of the attribute, in the form of an [expression][griffelib.Expr]. +- [`value`][griffelib.Attribute.value]: The value of the attribute, in the form of an [expression][griffelib.Expr]. +- [`deleter`][griffelib.Attribute.deleter]: The property deleter. +- [`setter`][griffelib.Attribute.setter]: The property setter. ### Type aliases -- [`value`][griffe.TypeAlias.value]: The value of the type alias, in the form of an [expression][griffe.Expr]. -- [`type_parameters`][griffe.TypeAlias.type_parameters]: The [type parameters][griffe.TypeParameters] of the type alias. +- [`value`][griffelib.TypeAlias.value]: The value of the type alias, in the form of an [expression][griffelib.Expr]. +- [`type_parameters`][griffelib.TypeAlias.type_parameters]: The [type parameters][griffelib.TypeParameters] of the type alias. ### Alias -- [`alias_lineno`][griffe.Alias.alias_lineno]: The alias line number (where the object is imported). -- [`alias_endlineno`][griffe.Alias.alias_endlineno]: The alias ending line number (where the object is imported). -- [`target`][griffe.Alias.target]: The alias target (a module, class, function or attribute). -- [`target_path`][griffe.Alias.target_path]: The path of the alias target, as a string. -- [`wildcard`][griffe.Alias.wildcard]: Whether this alias represents a wildcard import, and if so from which module. -- [`resolve_target()`][griffe.Alias.resolve_target]: A method that resolves the target when called. +- [`alias_lineno`][griffelib.Alias.alias_lineno]: The alias line number (where the object is imported). +- [`alias_endlineno`][griffelib.Alias.alias_endlineno]: The alias ending line number (where the object is imported). +- [`target`][griffelib.Alias.target]: The alias target (a module, class, function or attribute). +- [`target_path`][griffelib.Alias.target_path]: The path of the alias target, as a string. +- [`wildcard`][griffelib.Alias.wildcard]: Whether this alias represents a wildcard import, and if so from which module. +- [`resolve_target()`][griffelib.Alias.resolve_target]: A method that resolves the target when called. ## Expressions @@ -444,7 +444,7 @@ The Python language keeps evolving, and often library developers must continue s Yet this doesn't mean they can't enjoy latest features in their own docs: Griffe allows to "modernize" expressions, for example by replacing `typing.Union` with PEP 604 type unions `|`. Thanks to this, downstream tools like [mkdocstrings][mkdocstrings-python] can automatically transform type annotations into their modern equivalent. This improves consistency in your docs, and shows users how to use your code with the latest features of the language. -To modernize an expression, simply call its [`modernize()`][griffe.Expr.modernize] method. It returns a new, modernized expression. Some parts of the expression might be left unchanged, so be careful if you decide to mutate them. +To modernize an expression, simply call its [`modernize()`][griffelib.Expr.modernize] method. It returns a new, modernized expression. Some parts of the expression might be left unchanged, so be careful if you decide to mutate them. Modernizations applied: diff --git a/docs/guide/users/recommendations/public-apis.md b/docs/guide/users/recommendations/public-apis.md index 9a0d1cbbd..1876d0211 100644 --- a/docs/guide/users/recommendations/public-apis.md +++ b/docs/guide/users/recommendations/public-apis.md @@ -438,7 +438,7 @@ if __name__ == "__main__": sys.exit(main()) ``` -In this script, we find our entrypoint, `griffe.main`, used programmatically. +In this script, we find our entrypoint, `griffecli.main`, used programmatically. --- diff --git a/docs/guide/users/serializing.md b/docs/guide/users/serializing.md index 6adcfb4e6..f5008c46a 100644 --- a/docs/guide/users/serializing.md +++ b/docs/guide/users/serializing.md @@ -54,14 +54,14 @@ See all the options for the `dump` command in the [CLI reference](../../referenc If you have read through the [Navigating](navigating.md) chapter, you know about our six data models for modules, classes, functions, attributes, type aliases and aliases. Each one of these model provide the two following methods: -- [`as_json`][griffe.Object.as_json], which allows to serialize an object into JSON, -- [`from_json`][griffe.Object.from_json], which allows loading JSON back into a model instance. +- [`as_json`][griffelib.Object.as_json], which allows to serialize an object into JSON, +- [`from_json`][griffelib.Object.from_json], which allows loading JSON back into a model instance. -These two methods are convenient wrappers around our [JSON encoder][griffe.JSONEncoder] and [JSON decoder][griffe.json_decoder]. The JSON encoder and decoder will give you finer-grain control over what you serialize or load, as the methods above are only available on data models, and not on sub-structures like decorators or parameters. +These two methods are convenient wrappers around our [JSON encoder][griffelib.JSONEncoder] and [JSON decoder][griffelib.json_decoder]. The JSON encoder and decoder will give you finer-grain control over what you serialize or load, as the methods above are only available on data models, and not on sub-structures like decorators or parameters. -Under the hood, `as_json` just calls [`as_dict`][griffe.Object.as_dict], which converts the model instance into a dictionary, and then serializes this dictionary to JSON. +Under the hood, `as_json` just calls [`as_dict`][griffelib.Object.as_dict], which converts the model instance into a dictionary, and then serializes this dictionary to JSON. -When serializing an object, by default the JSON will only contain the fields required to load it back to a Griffe model instance. If you are not planning on loading back the data into our data models, or if you want to load them in a different implementation which is not able to infer back all the other fields, you can choose to serialize every possible field. We call this a full dump, and it is enabled with the `full` option of the [encoder][griffe.JSONEncoder] or the [`as_json`][griffe.Object.as_json] method. +When serializing an object, by default the JSON will only contain the fields required to load it back to a Griffe model instance. If you are not planning on loading back the data into our data models, or if you want to load them in a different implementation which is not able to infer back all the other fields, you can choose to serialize every possible field. We call this a full dump, and it is enabled with the `full` option of the [encoder][griffelib.JSONEncoder] or the [`as_json`][griffelib.Object.as_json] method. ## Schema diff --git a/docs/introduction.md b/docs/introduction.md index a7226fa6e..6ff2dd760 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -34,7 +34,7 @@ griffe.visit(...) griffe.inspect(...) ``` -To start exploring your API within Griffe data models, use the [`load`][griffe.load] function to load your package and access its various objects: +To start exploring your API within Griffe data models, use the [`load`][griffelib.load] function to load your package and access its various objects: ```python import griffe @@ -46,7 +46,7 @@ print(some_method.docstring.value) print(f"Is `some_method` public? {'yes' if some_method.is_public else 'no'}") ``` -Use the [`load_git`][griffe.load_git] function to load your API at a particular moment in time, specified with a Git reference (commit hash, branch name, tag name): +Use the [`load_git`][griffelib.load_git] function to load your API at a particular moment in time, specified with a Git reference (commit hash, branch name, tag name): ```python import griffe diff --git a/docs/reference/api/agents.md b/docs/reference/api/agents.md index 224426697..0a3d8c154 100644 --- a/docs/reference/api/agents.md +++ b/docs/reference/api/agents.md @@ -4,74 +4,74 @@ Griffe is able to analyze code both statically and dynamically. ## **Main API** -::: griffe.visit +::: griffelib.visit -::: griffe.inspect +::: griffelib.inspect ## **Advanced API** -::: griffe.Visitor +::: griffelib.Visitor -::: griffe.Inspector +::: griffelib.Inspector ## **Dynamic analysis helpers** -::: griffe.sys_path +::: griffelib.sys_path -::: griffe.dynamic_import +::: griffelib.dynamic_import -::: griffe.ObjectNode +::: griffelib.ObjectNode -::: griffe.ObjectKind +::: griffelib.ObjectKind ## **Static analysis helpers** -::: griffe.builtin_decorators +::: griffelib.builtin_decorators -::: griffe.stdlib_decorators +::: griffelib.stdlib_decorators -::: griffe.typing_overload +::: griffelib.typing_overload -::: griffe.ast_kind +::: griffelib.ast_kind -::: griffe.ast_children +::: griffelib.ast_children -::: griffe.ast_previous_siblings +::: griffelib.ast_previous_siblings -::: griffe.ast_next_siblings +::: griffelib.ast_next_siblings -::: griffe.ast_siblings +::: griffelib.ast_siblings -::: griffe.ast_previous +::: griffelib.ast_previous -::: griffe.ast_next +::: griffelib.ast_next -::: griffe.ast_first_child +::: griffelib.ast_first_child -::: griffe.ast_last_child +::: griffelib.ast_last_child -::: griffe.get_docstring +::: griffelib.get_docstring -::: griffe.get_name +::: griffelib.get_name -::: griffe.get_names +::: griffelib.get_names -::: griffe.get_instance_names +::: griffelib.get_instance_names -::: griffe.get__all__ +::: griffelib.get__all__ -::: griffe.safe_get__all__ +::: griffelib.safe_get__all__ -::: griffe.relative_to_absolute +::: griffelib.relative_to_absolute -::: griffe.get_parameters +::: griffelib.get_parameters -::: griffe.get_value +::: griffelib.get_value -::: griffe.safe_get_value +::: griffelib.safe_get_value ## **Deprecated API** -::: griffe.ExportedName +::: griffelib.ExportedName diff --git a/docs/reference/api/cli.md b/docs/reference/api/cli.md index 08e83a31a..c806e83cf 100644 --- a/docs/reference/api/cli.md +++ b/docs/reference/api/cli.md @@ -2,12 +2,12 @@ ## **Main API** -::: griffe.main +::: griffecli.main -::: griffe.check +::: griffecli.check -::: griffe.dump +::: griffecli.dump ## **Advanced API** -::: griffe.get_parser +::: griffecli.get_parser diff --git a/docs/reference/api/expressions.md b/docs/reference/api/expressions.md index 3b010a5d0..d91795c79 100644 --- a/docs/reference/api/expressions.md +++ b/docs/reference/api/expressions.md @@ -1,6 +1,6 @@ # Expressions -::: griffe._internal.expressions +::: griffelib._internal.expressions options: members: false show_root_heading: false diff --git a/docs/reference/api/models.md b/docs/reference/api/models.md index 3b7f35316..177d3b20c 100644 --- a/docs/reference/api/models.md +++ b/docs/reference/api/models.md @@ -10,12 +10,12 @@ Indirections to objects declared in other modules are represented as "aliases". The 6 models: -- [`Module`][griffe.Module] -- [`Class`][griffe.Class] -- [`Function`][griffe.Function] -- [`Attribute`][griffe.Attribute] -- [`Alias`][griffe.Alias] -- [`TypeAlias`][griffe.TypeAlias] +- [`Module`][griffelib.Module] +- [`Class`][griffelib.Class] +- [`Function`][griffelib.Function] +- [`Attribute`][griffelib.Attribute] +- [`Alias`][griffelib.Alias] +- [`TypeAlias`][griffelib.TypeAlias] ## **Model kind enumeration** diff --git a/docs/reference/api/serializers.md b/docs/reference/api/serializers.md index c9fff7b4e..ebd98fa4f 100644 --- a/docs/reference/api/serializers.md +++ b/docs/reference/api/serializers.md @@ -2,7 +2,7 @@ ## **Main API** -See the [`as_json()`][griffe.Object.as_json] and [`from_json()`][griffe.Object.from_json] methods of objects. +See the [`as_json()`][griffelib.Object.as_json] and [`from_json()`][griffelib.Object.from_json] methods of objects. ## **Advanced API** diff --git a/packages/griffelib/src/griffelib/__init__.py b/packages/griffelib/src/griffelib/__init__.py index d2a9665ef..2fe136df4 100644 --- a/packages/griffelib/src/griffelib/__init__.py +++ b/packages/griffelib/src/griffelib/__init__.py @@ -24,64 +24,64 @@ Griffe provides a command-line interface (CLI) to interact with the package. The CLI entrypoints can be called from Python code. -- [`griffe.main`][]: Run the main program. -- [`griffe.check`][]: Check for API breaking changes in two versions of the same package. -- [`griffe.dump`][]: Load packages data and dump it as JSON. +- [`griffecli.main`][]: Run the main program. +- [`griffecli.check`][]: Check for API breaking changes in two versions of the same package. +- [`griffecli.dump`][]: Load packages data and dump it as JSON. ## Loaders To load API data, Griffe provides several high-level functions. -- [`griffe.load`][]: Load and return a Griffe object. -- [`griffe.load_git`][]: Load and return a module from a specific Git reference. -- [`griffe.load_pypi`][]: Load and return a module from a specific package version downloaded using pip. +- [`griffelib.load`][]: Load and return a Griffe object. +- [`griffelib.load_git`][]: Load and return a module from a specific Git reference. +- [`griffelib.load_pypi`][]: Load and return a module from a specific package version downloaded using pip. ## Models The data loaded by Griffe is represented by several classes. -- [`griffe.Module`][]: The class representing a Python module. -- [`griffe.Class`][]: The class representing a Python class. -- [`griffe.Function`][]: The class representing a Python function or method. -- [`griffe.Attribute`][]: The class representing a Python attribute. -- [`griffe.Alias`][]: This class represents an alias, or indirection, to an object declared in another module. +- [`griffelib.Module`][]: The class representing a Python module. +- [`griffelib.Class`][]: The class representing a Python class. +- [`griffelib.Function`][]: The class representing a Python function or method. +- [`griffelib.Attribute`][]: The class representing a Python attribute. +- [`griffelib.Alias`][]: This class represents an alias, or indirection, to an object declared in another module. Additional classes are available to represent other concepts. -- [`griffe.Decorator`][]: This class represents a decorator. -- [`griffe.Parameters`][]: This class is a container for parameters. -- [`griffe.Parameter`][]: This class represent a function parameter. +- [`griffelib.Decorator`][]: This class represents a decorator. +- [`griffelib.Parameters`][]: This class is a container for parameters. +- [`griffelib.Parameter`][]: This class represent a function parameter. ## Agents Griffe is able to analyze code both statically and dynamically, using the following "agents". However most of the time you will only need to use the loaders above. -- [`griffe.visit`][]: Parse and visit a module file. -- [`griffe.inspect`][]: Inspect a module. +- [`griffelib.visit`][]: Parse and visit a module file. +- [`griffelib.inspect`][]: Inspect a module. ## Serializers Griffe can serizalize data to dictionary and JSON. -- [`griffe.Object.as_json`][griffe.Object.as_json] -- [`griffe.Object.from_json`][griffe.Object.from_json] -- [`griffe.JSONEncoder`][]: JSON encoder for Griffe objects. -- [`griffe.json_decoder`][]: JSON decoder for Griffe objects. +- [`griffelib.Object.as_json`][griffelib.Object.as_json] +- [`griffelib.Object.from_json`][griffelib.Object.from_json] +- [`griffelib.JSONEncoder`][]: JSON encoder for Griffe objects. +- [`griffelib.json_decoder`][]: JSON decoder for Griffe objects. ## API checks Griffe can compare two versions of the same package to find breaking changes. -- [`griffe.find_breaking_changes`][]: Find breaking changes between two versions of the same API. -- [`griffe.Breakage`][]: Breakage classes can explain what broke from a version to another. +- [`griffelib.find_breaking_changes`][]: Find breaking changes between two versions of the same API. +- [`griffelib.Breakage`][]: Breakage classes can explain what broke from a version to another. ## Extensions -Griffe supports extensions. You can create your own extension by subclassing the `griffe.Extension` class. +Griffe supports extensions. You can create your own extension by subclassing the `griffelib.Extension` class. -- [`griffe.load_extensions`][]: Load configured extensions. -- [`griffe.Extension`][]: Base class for Griffe extensions. +- [`griffelib.load_extensions`][]: Load configured extensions. +- [`griffelib.Extension`][]: Base class for Griffe extensions. ## Docstrings @@ -89,35 +89,35 @@ Main class: -- [`griffe.Docstring`][]: This class represents docstrings. +- [`griffelib.Docstring`][]: This class represents docstrings. Docstring section and element classes all start with `Docstring`. Docstring parsers: -- [`griffe.parse`][]: Parse the docstring. -- [`griffe.parse_auto`][]: Parse a docstring by automatically detecting the style it uses. -- [`griffe.parse_google`][]: Parse a Google-style docstring. -- [`griffe.parse_numpy`][]: Parse a Numpydoc-style docstring. -- [`griffe.parse_sphinx`][]: Parse a Sphinx-style docstring. +- [`griffelib.parse`][]: Parse the docstring. +- [`griffelib.parse_auto`][]: Parse a docstring by automatically detecting the style it uses. +- [`griffelib.parse_google`][]: Parse a Google-style docstring. +- [`griffelib.parse_numpy`][]: Parse a Numpydoc-style docstring. +- [`griffelib.parse_sphinx`][]: Parse a Sphinx-style docstring. ## Exceptions Griffe uses several exceptions to signal errors. -- [`griffe.GriffeError`][]: The base exception for all Griffe errors. -- [`griffe.LoadingError`][]: Exception for loading errors. -- [`griffe.NameResolutionError`][]: Exception for names that cannot be resolved in a object scope. -- [`griffe.UnhandledEditableModuleError`][]: Exception for unhandled editables modules, when searching modules. -- [`griffe.UnimportableModuleError`][]: Exception for modules that cannot be imported. -- [`griffe.AliasResolutionError`][]: Exception for aliases that cannot be resolved. -- [`griffe.CyclicAliasError`][]: Exception raised when a cycle is detected in aliases. -- [`griffe.LastNodeError`][]: Exception raised when trying to access a next or previous node. -- [`griffe.RootNodeError`][]: Exception raised when trying to use siblings properties on a root node. -- [`griffe.BuiltinModuleError`][]: Exception raised when trying to access the filepath of a builtin module. -- [`griffe.ExtensionError`][]: Base class for errors raised by extensions. -- [`griffe.ExtensionNotLoadedError`][]: Exception raised when an extension could not be loaded. -- [`griffe.GitError`][]: Exception raised for errors related to Git. +- [`griffelib.GriffeError`][]: The base exception for all Griffe errors. +- [`griffelib.LoadingError`][]: Exception for loading errors. +- [`griffelib.NameResolutionError`][]: Exception for names that cannot be resolved in a object scope. +- [`griffelib.UnhandledEditableModuleError`][]: Exception for unhandled editables modules, when searching modules. +- [`griffelib.UnimportableModuleError`][]: Exception for modules that cannot be imported. +- [`griffelib.AliasResolutionError`][]: Exception for aliases that cannot be resolved. +- [`griffelib.CyclicAliasError`][]: Exception raised when a cycle is detected in aliases. +- [`griffelib.LastNodeError`][]: Exception raised when trying to access a next or previous node. +- [`griffelib.RootNodeError`][]: Exception raised when trying to use siblings properties on a root node. +- [`griffelib.BuiltinModuleError`][]: Exception raised when trying to access the filepath of a builtin module. +- [`griffelib.ExtensionError`][]: Base class for errors raised by extensions. +- [`griffelib.ExtensionNotLoadedError`][]: Exception raised when an extension could not be loaded. +- [`griffelib.GitError`][]: Exception raised for errors related to Git. # Expressions @@ -125,20 +125,20 @@ Expressions are basically abstract syntax trees (AST) with a few differences compared to the nodes returned by [`ast`][]. Griffe provides a few helpers to extract expressions from regular AST nodes. -- [`griffe.get_annotation`][]: Get a type annotation as expression. -- [`griffe.get_base_class`][]: Get a base class as expression. -- [`griffe.get_class_keyword`][]: Get a class keyword as expression. -- [`griffe.get_condition`][]: Get a condition as expression. -- [`griffe.get_expression`][]: Get an expression from an AST node. -- [`griffe.safe_get_annotation`][]: Get a type annotation as expression, safely (returns `None` on error). -- [`griffe.safe_get_base_class`][]: Get a base class as expression, safely (returns `None` on error). -- [`griffe.safe_get_class_keyword`][]: Get a class keyword as expression, safely (returns `None` on error). -- [`griffe.safe_get_condition`][]: Get a condition as expression, safely (returns `None` on error). -- [`griffe.safe_get_expression`][]: Get an expression from an AST node, safely (returns `None` on error). +- [`griffelib.get_annotation`][]: Get a type annotation as expression. +- [`griffelib.get_base_class`][]: Get a base class as expression. +- [`griffelib.get_class_keyword`][]: Get a class keyword as expression. +- [`griffelib.get_condition`][]: Get a condition as expression. +- [`griffelib.get_expression`][]: Get an expression from an AST node. +- [`griffelib.safe_get_annotation`][]: Get a type annotation as expression, safely (returns `None` on error). +- [`griffelib.safe_get_base_class`][]: Get a base class as expression, safely (returns `None` on error). +- [`griffelib.safe_get_class_keyword`][]: Get a class keyword as expression, safely (returns `None` on error). +- [`griffelib.safe_get_condition`][]: Get a condition as expression, safely (returns `None` on error). +- [`griffelib.safe_get_expression`][]: Get an expression from an AST node, safely (returns `None` on error). The base class for expressions. -- [`griffe.Expr`][] +- [`griffelib.Expr`][] Expression classes all start with `Expr`. @@ -147,19 +147,19 @@ If you want to log messages from extensions, get a logger with `get_logger`. The `logger` attribute is used by Griffe itself. You can use it to temporarily disable Griffe logging. -- [`griffe.logger`][]: Our global logger, used throughout the library. -- [`griffe.get_logger`][]: Create and return a new logger instance. +- [`griffelib.logger`][]: Our global logger, used throughout the library. +- [`griffelib.get_logger`][]: Create and return a new logger instance. # Helpers To test your Griffe extensions, or to load API data from code in memory, Griffe provides the following helpers. -- [`griffe.temporary_pyfile`][]: Create a Python file containing the given code in a temporary directory. -- [`griffe.temporary_pypackage`][]: Create a package containing the given modules in a temporary directory. -- [`griffe.temporary_visited_module`][]: Create and visit a temporary module with the given code. -- [`griffe.temporary_visited_package`][]: Create and visit a temporary package. -- [`griffe.temporary_inspected_module`][]: Create and inspect a temporary module with the given code. -- [`griffe.temporary_inspected_package`][]: Create and inspect a temporary package. +- [`griffelib.temporary_pyfile`][]: Create a Python file containing the given code in a temporary directory. +- [`griffelib.temporary_pypackage`][]: Create a package containing the given modules in a temporary directory. +- [`griffelib.temporary_visited_module`][]: Create and visit a temporary module with the given code. +- [`griffelib.temporary_visited_package`][]: Create and visit a temporary package. +- [`griffelib.temporary_inspected_module`][]: Create and inspect a temporary module with the given code. +- [`griffelib.temporary_inspected_package`][]: Create and inspect a temporary package. """ from __future__ import annotations diff --git a/packages/griffelib/src/griffelib/_internal/agents/inspector.py b/packages/griffelib/src/griffelib/_internal/agents/inspector.py index 896b5a5e2..7eb5df5c2 100644 --- a/packages/griffelib/src/griffelib/_internal/agents/inspector.py +++ b/packages/griffelib/src/griffelib/_internal/agents/inspector.py @@ -75,16 +75,16 @@ def inspect( In this case, we load the module using introspection. Griffe therefore provides this function for dynamic analysis. - It uses a [`NodeVisitor`][ast.NodeVisitor]-like class, the [`Inspector`][griffe.Inspector], + It uses a [`NodeVisitor`][ast.NodeVisitor]-like class, the [`Inspector`][griffelib.Inspector], to inspect the module with [`inspect.getmembers()`][inspect.getmembers]. - The inspection agent works similarly to the regular [`Visitor`][griffe.Visitor] agent, + The inspection agent works similarly to the regular [`Visitor`][griffelib.Visitor] agent, in that it maintains a state with the current object being handled, and recursively handle its members. Important: This function is generally not used directly. - In most cases, users can rely on the [`GriffeLoader`][griffe.GriffeLoader] - and its accompanying [`load`][griffe.load] shortcut and their respective options + In most cases, users can rely on the [`GriffeLoader`][griffelib.GriffeLoader] + and its accompanying [`load`][griffelib.load] shortcut and their respective options to load modules using dynamic analysis. Parameters: diff --git a/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py index 8001ad5f8..99fb18ddb 100644 --- a/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py @@ -21,7 +21,7 @@ class ExportedName: """Deprecated. An intermediate class to store names. - The [`get__all__`][griffe.get__all__] function now returns instances of [`ExprName`][griffe.ExprName] instead. + The [`get__all__`][griffelib.get__all__] function now returns instances of [`ExprName`][griffelib.ExprName] instead. """ name: str diff --git a/packages/griffelib/src/griffelib/_internal/agents/visitor.py b/packages/griffelib/src/griffelib/_internal/agents/visitor.py index b6b2e537c..f1a9e18ff 100644 --- a/packages/griffelib/src/griffelib/_internal/agents/visitor.py +++ b/packages/griffelib/src/griffelib/_internal/agents/visitor.py @@ -92,13 +92,13 @@ def visit( """Parse and visit a module file. We provide this function for static analysis. It uses a [`NodeVisitor`][ast.NodeVisitor]-like class, - the [`Visitor`][griffe.Visitor], to compile and parse code (using [`compile`][]) + the [`Visitor`][griffelib.Visitor], to compile and parse code (using [`compile`][]) then visit the resulting AST (Abstract Syntax Tree). Important: This function is generally not used directly. - In most cases, users can rely on the [`GriffeLoader`][griffe.GriffeLoader] - and its accompanying [`load`][griffe.load] shortcut and their respective options + In most cases, users can rely on the [`GriffeLoader`][griffelib.GriffeLoader] + and its accompanying [`load`][griffelib.load] shortcut and their respective options to load modules using static analysis. Parameters: diff --git a/packages/griffelib/src/griffelib/_internal/docstrings/auto.py b/packages/griffelib/src/griffelib/_internal/docstrings/auto.py index 0bc888021..ca2970f54 100644 --- a/packages/griffelib/src/griffelib/_internal/docstrings/auto.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/auto.py @@ -208,7 +208,7 @@ def parse_auto( ) -> list[DocstringSection]: """Parse a docstring by automatically detecting the style it uses. - See [`infer_docstring_style`][griffe.infer_docstring_style] for more information + See [`infer_docstring_style`][griffelib.infer_docstring_style] for more information on the available parameters. Parameters: diff --git a/packages/griffelib/src/griffelib/_internal/encoders.py b/packages/griffelib/src/griffelib/_internal/encoders.py index 356233dfb..5b3ef641c 100644 --- a/packages/griffelib/src/griffelib/_internal/encoders.py +++ b/packages/griffelib/src/griffelib/_internal/encoders.py @@ -61,7 +61,7 @@ def __init__( *args: See [`json.JSONEncoder`][]. full: Whether to dump full data or base data. If you plan to reload the data in Python memory - using the [`json_decoder`][griffe.json_decoder], + using the [`json_decoder`][griffelib.json_decoder], you don't need the full data as it can be inferred again using the base data. If you want to feed a non-Python tool instead, dump the full data. diff --git a/packages/griffelib/src/griffelib/_internal/expressions.py b/packages/griffelib/src/griffelib/_internal/expressions.py index 2d2ebf7dd..4e67bbb18 100644 --- a/packages/griffelib/src/griffelib/_internal/expressions.py +++ b/packages/griffelib/src/griffelib/_internal/expressions.py @@ -180,7 +180,7 @@ def iterate(self, *, flat: bool = True) -> Iterator[str | Expr]: # noqa: ARG002 without them getting rendered as strings. On the contrary, when flat is true, the whole tree is flattened as a sequence - of strings and instances of [Names][griffe.ExprName]. + of strings and instances of [Names][griffelib.ExprName]. Yields: Strings and names when flat, strings and expressions otherwise. diff --git a/packages/griffelib/src/griffelib/_internal/extensions/base.py b/packages/griffelib/src/griffelib/_internal/extensions/base.py index e5ff82b09..50a68c73b 100644 --- a/packages/griffelib/src/griffelib/_internal/extensions/base.py +++ b/packages/griffelib/src/griffelib/_internal/extensions/base.py @@ -587,7 +587,7 @@ def _load_extension( # If the import path corresponds to a built-in extension, expand it. if import_path in builtin_extensions: - import_path = f"griffe._internal.extensions.{import_path}" + import_path = f"griffelib._internal.extensions.{import_path}" # If the import path is a path to an existing file, load it. elif os.path.exists(import_path): # noqa: PTH110 try: diff --git a/packages/griffelib/src/griffelib/_internal/finder.py b/packages/griffelib/src/griffelib/_internal/finder.py index 198d15fa6..575fde0dc 100644 --- a/packages/griffelib/src/griffelib/_internal/finder.py +++ b/packages/griffelib/src/griffelib/_internal/finder.py @@ -89,9 +89,9 @@ class ModuleFinder: """The Griffe finder, allowing to find modules on the file system. The module finder is generally not used directly. - Each [`GriffeLoader`][griffe.GriffeLoader] instance creates its own module finder instance. + Each [`GriffeLoader`][griffelib.GriffeLoader] instance creates its own module finder instance. The finder can be configured when instantiating the loader - thanks to the [loader][griffe.GriffeLoader]'s `search_paths` parameter. + thanks to the [loader][griffelib.GriffeLoader]'s `search_paths` parameter. """ accepted_py_module_extensions: ClassVar[list[str]] = [".py", ".pyc", ".pyo", ".pyd", ".pyi", ".so"] diff --git a/packages/griffelib/src/griffelib/_internal/git.py b/packages/griffelib/src/griffelib/_internal/git.py index d3ab094db..7ea952efa 100644 --- a/packages/griffelib/src/griffelib/_internal/git.py +++ b/packages/griffelib/src/griffelib/_internal/git.py @@ -1,4 +1,4 @@ -# This module contains Git utilities, used by our [`load_git`][griffe.load_git] function, +# This module contains Git utilities, used by our [`load_git`][griffelib.load_git] function, # which in turn is used to load the API for different snapshots of a Git repository # and find breaking changes between them. diff --git a/packages/griffelib/src/griffelib/_internal/importer.py b/packages/griffelib/src/griffelib/_internal/importer.py index b75b44ee2..4144357c3 100644 --- a/packages/griffelib/src/griffelib/_internal/importer.py +++ b/packages/griffelib/src/griffelib/_internal/importer.py @@ -1,5 +1,5 @@ # This module contains utilities to dynamically import objects. -# These utilities are used by our [`Inspector`][griffe.Inspector] to dynamically import objects +# These utilities are used by our [`Inspector`][griffelib.Inspector] to dynamically import objects # specified as Python paths, like `package.module.Class.method`. from __future__ import annotations diff --git a/packages/griffelib/src/griffelib/_internal/loader.py b/packages/griffelib/src/griffelib/_internal/loader.py index e25245a6a..c82b502ce 100644 --- a/packages/griffelib/src/griffelib/_internal/loader.py +++ b/packages/griffelib/src/griffelib/_internal/loader.py @@ -120,7 +120,7 @@ def load( Examples: >>> loader.load("griffe.Module") - Alias("Module", "griffe._internal.models.Module") + Alias("Module", "griffelib._internal.models.Module") Parameters: objspec: The Python path of an object, or file path to a module. @@ -293,7 +293,7 @@ def resolve_aliases( def expand_exports(self, module: Module, seen: set | None = None) -> None: """Expand exports: try to recursively expand all module exports (`__all__` values). - See also: [`Module.exports`][griffe.Module.exports]. + See also: [`Module.exports`][griffelib.Module.exports]. Parameters: module: The module to recurse on. @@ -340,7 +340,7 @@ def expand_wildcards( ) -> None: """Expand wildcards: try to recursively expand all found wildcards. - See also: [`Alias.wildcard`][griffe.Alias.wildcard]. + See also: [`Alias.wildcard`][griffelib.Alias.wildcard]. Parameters: obj: The object and its members to recurse on. @@ -771,19 +771,19 @@ def load( In Griffe's context, loading means: - searching for a package, and finding it on the file system or as a builtin module - (see the [`ModuleFinder`][griffe.ModuleFinder] class for more information) + (see the [`ModuleFinder`][griffelib.ModuleFinder] class for more information) - extracting information from each of its (sub)modules, by either parsing - the source code (see the [`visit`][griffe.visit] function) - or inspecting the module at runtime (see the [`inspect`][griffe.inspect] function) + the source code (see the [`visit`][griffelib.visit] function) + or inspecting the module at runtime (see the [`inspect`][griffelib.inspect] function) The extracted information is stored in a collection of modules, which can be queried later. Each collected module is a tree of objects, representing the structure of the module. - See the [`Module`][griffe.Module], [`Class`][griffe.Class], - [`Function`][griffe.Function], [`Attribute`][griffe.Attribute], and - [`TypeAlias`][griffe.TypeAlias] classes for more information. + See the [`Module`][griffelib.Module], [`Class`][griffelib.Class], + [`Function`][griffelib.Function], [`Attribute`][griffelib.Attribute], and + [`TypeAlias`][griffelib.TypeAlias] classes for more information. - The main class used to load modules is [`GriffeLoader`][griffe.GriffeLoader]. - Convenience functions like this one and [`load_git`][griffe.load_git] are also available. + The main class used to load modules is [`GriffeLoader`][griffelib.GriffeLoader]. + Convenience functions like this one and [`load_git`][griffelib.load_git] are also available. Example: ```python @@ -801,7 +801,7 @@ def load( module = loader.load(...) ``` - See the documentation for the loader: [`GriffeLoader`][griffe.GriffeLoader]. + See the documentation for the loader: [`GriffeLoader`][griffelib.GriffeLoader]. Parameters: objspec: The Python path of an object, or file path to a module. @@ -875,7 +875,7 @@ def load_git( This function will create a temporary [git worktree](https://git-scm.com/docs/git-worktree) at the requested reference - before loading `module` with [`griffe.load`][griffe.load]. + before loading `module` with [`griffe.load`][griffelib.load]. This function requires that the `git` executable is installed. diff --git a/packages/griffelib/src/griffelib/_internal/logger.py b/packages/griffelib/src/griffelib/_internal/logger.py index c6679104f..58bf8eae4 100644 --- a/packages/griffelib/src/griffelib/_internal/logger.py +++ b/packages/griffelib/src/griffelib/_internal/logger.py @@ -60,7 +60,7 @@ def _patch_loggers(cls, get_logger_func: Callable) -> None: Griffe's output and error messages are logging messages. -Griffe provides the [`patch_loggers`][griffe.patch_loggers] +Griffe provides the [`patch_loggers`][griffelib.patch_loggers] function so dependent libraries can patch Griffe loggers as they see fit. For example, to fit in the MkDocs logging configuration diff --git a/packages/griffelib/src/griffelib/_internal/models.py b/packages/griffelib/src/griffelib/_internal/models.py index ce254fddd..4e50979c9 100644 --- a/packages/griffelib/src/griffelib/_internal/models.py +++ b/packages/griffelib/src/griffelib/_internal/models.py @@ -12,9 +12,23 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, Union, cast from griffelib._internal.c3linear import c3linear_merge -from griffelib._internal.docstrings.parsers import DocstringOptions, DocstringStyle, parse -from griffelib._internal.enumerations import Kind, ParameterKind, Parser, TypeParameterKind -from griffelib._internal.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError, NameResolutionError +from griffelib._internal.docstrings.parsers import ( + DocstringOptions, + DocstringStyle, + parse, +) +from griffelib._internal.enumerations import ( + Kind, + ParameterKind, + Parser, + TypeParameterKind, +) +from griffelib._internal.exceptions import ( + AliasResolutionError, + BuiltinModuleError, + CyclicAliasError, + NameResolutionError, +) from griffelib._internal.expressions import ExprCall, ExprName, ExprTuple from griffelib._internal.logger import logger from griffelib._internal.mixins import ObjectAliasMixin @@ -97,18 +111,18 @@ def __init__( self.value: str = inspect.cleandoc(value.rstrip()) """The original value of the docstring, cleaned by `inspect.cleandoc`. - See also: [`source`][griffe.Docstring.source]. + See also: [`source`][griffelib.Docstring.source]. """ self.lineno: int | None = lineno """The starting line number of the docstring. - See also: [`endlineno`][griffe.Docstring.endlineno].""" + See also: [`endlineno`][griffelib.Docstring.endlineno].""" self.endlineno: int | None = endlineno """The ending line number of the docstring. - See also: [`lineno`][griffe.Docstring.lineno].""" + See also: [`lineno`][griffelib.Docstring.lineno].""" self.parent: Object | None = parent """The object this docstring is attached to.""" @@ -116,22 +130,22 @@ def __init__( self.parser: DocstringStyle | Parser | None = parser """The selected docstring parser. - See also: [`parser_options`][griffe.Docstring.parser_options], - [`parse`][griffe.Docstring.parse]. + See also: [`parser_options`][griffelib.Docstring.parser_options], + [`parse`][griffelib.Docstring.parse]. """ self.parser_options: DocstringOptions = parser_options or {} """The configured parsing options. - See also: [`parser`][griffe.Docstring.parser], - [`parse`][griffe.Docstring.parse]. + See also: [`parser`][griffelib.Docstring.parser], + [`parse`][griffelib.Docstring.parse]. """ @property def lines(self) -> list[str]: """The lines of the docstring. - See also: [`source`][griffe.Docstring.source]. + See also: [`source`][griffelib.Docstring.source]. """ return self.value.split("\n") @@ -147,7 +161,7 @@ def source(self) -> str: ValueError: If the original docstring cannot be retrieved (no parent, no line numbers, or attached to namespace package). - See also: [`value`][griffe.Docstring.value]. + See also: [`value`][griffelib.Docstring.value]. """ if self.parent is None: raise ValueError("Cannot get original docstring without parent object") @@ -169,8 +183,8 @@ def parse( ) -> list[DocstringSection]: """Parse the docstring into structured data. - See also: [`parser`][griffe.Docstring.parser], - [`parser_options`][griffe.Docstring.parser_options]. + See also: [`parser`][griffelib.Docstring.parser], + [`parser_options`][griffelib.Docstring.parser_options]. Parameters: parser: The docstring parser to use. @@ -210,7 +224,7 @@ def as_dict( class Parameter: # noqa: PLW1641 """This class represent a function parameter. - See also: [`Parameters`][griffe.Parameters]. + See also: [`Parameters`][griffelib.Parameters]. """ def __init__( @@ -302,7 +316,7 @@ class Parameters: True ``` - See also: [`Parameter`][griffe.Parameter]. + See also: [`Parameter`][griffelib.Parameter]. """ def __init__(self, *parameters: Parameter) -> None: @@ -613,20 +627,20 @@ def __init__( self.lineno: int | None = lineno """The starting line number of the object. - See also: [`endlineno`][griffe.Object.endlineno]. + See also: [`endlineno`][griffelib.Object.endlineno]. """ self.endlineno: int | None = endlineno """The ending line number of the object. - See also: [`lineno`][griffe.Object.lineno]. + See also: [`lineno`][griffelib.Object.lineno]. """ self.docstring: Docstring | None = docstring """The object docstring. - See also: [`has_docstring`][griffe.Object.has_docstring], - [`has_docstrings`][griffe.Object.has_docstrings]. + See also: [`has_docstring`][griffelib.Object.has_docstring], + [`has_docstrings`][griffelib.Object.has_docstrings]. """ # TODO: Maybe move these into `Class` and `Function`. @@ -641,16 +655,16 @@ def __init__( self.members: dict[str, Object | Alias] = {} """The object members (modules, classes, functions, attributes, type aliases). - See also: [`inherited_members`][griffe.Object.inherited_members], - [`get_member`][griffe.Object.get_member], - [`set_member`][griffe.Object.set_member], - [`filter_members`][griffe.Object.filter_members]. + See also: [`inherited_members`][griffelib.Object.inherited_members], + [`get_member`][griffelib.Object.get_member], + [`set_member`][griffelib.Object.set_member], + [`filter_members`][griffelib.Object.filter_members]. """ self.labels: set[str] = set() """The object labels (`property`, `dataclass`, etc.). - See also: [`has_labels`][griffe.Object.has_labels].""" + See also: [`has_labels`][griffelib.Object.has_labels].""" self.imports: dict[str, str] = {} """The other objects imported by this object. @@ -673,7 +687,7 @@ def __init__( Exports get expanded by the loader before it expands wildcards and resolves aliases. - See also: [`GriffeLoader.expand_exports`][griffe.GriffeLoader.expand_exports]. + See also: [`GriffeLoader.expand_exports`][griffelib.GriffeLoader.expand_exports]. """ self.aliases: dict[str, Alias] = {} @@ -757,8 +771,8 @@ def source_link(self, value: str | None) -> None: def has_docstring(self) -> bool: """Whether this object has a docstring (empty or not). - See also: [`docstring`][griffe.Object.docstring], - [`has_docstrings`][griffe.Object.has_docstrings]. + See also: [`docstring`][griffelib.Object.docstring], + [`has_docstrings`][griffelib.Object.has_docstrings]. """ return bool(self.docstring) @@ -777,8 +791,8 @@ def has_docstrings(self) -> bool: Inherited members are not considered. Imported members are not considered, unless they are also public. - See also: [`docstring`][griffe.Object.docstring], - [`has_docstring`][griffe.Object.has_docstring]. + See also: [`docstring`][griffelib.Object.docstring], + [`has_docstring`][griffelib.Object.has_docstring]. """ if self.has_docstring: return True @@ -793,12 +807,12 @@ def has_docstrings(self) -> bool: def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool: """Tell if this object is of the given kind. - See also: [`is_module`][griffe.Object.is_module], - [`is_class`][griffe.Object.is_class], - [`is_function`][griffe.Object.is_function], - [`is_attribute`][griffe.Object.is_attribute], - [`is_type_alias`][griffe.Object.is_type_alias], - [`is_alias`][griffe.Object.is_alias]. + See also: [`is_module`][griffelib.Object.is_module], + [`is_class`][griffelib.Object.is_class], + [`is_function`][griffelib.Object.is_function], + [`is_attribute`][griffelib.Object.is_attribute], + [`is_type_alias`][griffelib.Object.is_type_alias], + [`is_alias`][griffelib.Object.is_alias]. Parameters: kind: An instance or set of kinds (strings or enumerations). @@ -824,7 +838,7 @@ def inherited_members(self) -> dict[str, Alias]: This method is part of the consumer API: do not use when producing Griffe trees! - See also: [`members`][griffe.Object.members]. + See also: [`members`][griffelib.Object.members]. """ if not isinstance(self, Class): return {} @@ -844,13 +858,13 @@ def inherited_members(self) -> dict[str, Alias]: def is_module(self) -> bool: """Whether this object is a module. - See also: [`is_init_module`][griffe.Object.is_init_module]. - [`is_class`][griffe.Object.is_class], - [`is_function`][griffe.Object.is_function], - [`is_attribute`][griffe.Object.is_attribute], - [`is_type_alias`][griffe.Object.is_type_alias], - [`is_alias`][griffe.Object.is_alias], - [`is_kind`][griffe.Object.is_kind]. + See also: [`is_init_module`][griffelib.Object.is_init_module]. + [`is_class`][griffelib.Object.is_class], + [`is_function`][griffelib.Object.is_function], + [`is_attribute`][griffelib.Object.is_attribute], + [`is_type_alias`][griffelib.Object.is_type_alias], + [`is_alias`][griffelib.Object.is_alias], + [`is_kind`][griffelib.Object.is_kind]. """ return self.kind is Kind.MODULE @@ -858,12 +872,12 @@ def is_module(self) -> bool: def is_class(self) -> bool: """Whether this object is a class. - See also: [`is_module`][griffe.Object.is_module]. - [`is_function`][griffe.Object.is_function], - [`is_attribute`][griffe.Object.is_attribute], - [`is_type_alias`][griffe.Object.is_type_alias], - [`is_alias`][griffe.Object.is_alias], - [`is_kind`][griffe.Object.is_kind]. + See also: [`is_module`][griffelib.Object.is_module]. + [`is_function`][griffelib.Object.is_function], + [`is_attribute`][griffelib.Object.is_attribute], + [`is_type_alias`][griffelib.Object.is_type_alias], + [`is_alias`][griffelib.Object.is_alias], + [`is_kind`][griffelib.Object.is_kind]. """ return self.kind is Kind.CLASS @@ -871,12 +885,12 @@ def is_class(self) -> bool: def is_function(self) -> bool: """Whether this object is a function. - See also: [`is_module`][griffe.Object.is_module]. - [`is_class`][griffe.Object.is_class], - [`is_attribute`][griffe.Object.is_attribute], - [`is_type_alias`][griffe.Object.is_type_alias], - [`is_alias`][griffe.Object.is_alias], - [`is_kind`][griffe.Object.is_kind]. + See also: [`is_module`][griffelib.Object.is_module]. + [`is_class`][griffelib.Object.is_class], + [`is_attribute`][griffelib.Object.is_attribute], + [`is_type_alias`][griffelib.Object.is_type_alias], + [`is_alias`][griffelib.Object.is_alias], + [`is_kind`][griffelib.Object.is_kind]. """ return self.kind is Kind.FUNCTION @@ -884,12 +898,12 @@ def is_function(self) -> bool: def is_attribute(self) -> bool: """Whether this object is an attribute. - See also: [`is_module`][griffe.Object.is_module]. - [`is_class`][griffe.Object.is_class], - [`is_function`][griffe.Object.is_function], - [`is_type_alias`][griffe.Object.is_type_alias], - [`is_alias`][griffe.Object.is_alias], - [`is_kind`][griffe.Object.is_kind]. + See also: [`is_module`][griffelib.Object.is_module]. + [`is_class`][griffelib.Object.is_class], + [`is_function`][griffelib.Object.is_function], + [`is_type_alias`][griffelib.Object.is_type_alias], + [`is_alias`][griffelib.Object.is_alias], + [`is_kind`][griffelib.Object.is_kind]. """ return self.kind is Kind.ATTRIBUTE @@ -897,12 +911,12 @@ def is_attribute(self) -> bool: def is_type_alias(self) -> bool: """Whether this object is a type alias. - See also: [`is_module`][griffe.Object.is_module]. - [`is_class`][griffe.Object.is_class], - [`is_function`][griffe.Object.is_function], - [`is_attribute`][griffe.Object.is_attribute], - [`is_alias`][griffe.Object.is_alias], - [`is_kind`][griffe.Object.is_kind]. + See also: [`is_module`][griffelib.Object.is_module]. + [`is_class`][griffelib.Object.is_class], + [`is_function`][griffelib.Object.is_function], + [`is_attribute`][griffelib.Object.is_attribute], + [`is_alias`][griffelib.Object.is_alias], + [`is_kind`][griffelib.Object.is_kind]. """ return self.kind is Kind.TYPE_ALIAS @@ -915,7 +929,7 @@ def is_init_method(self) -> bool: def is_init_module(self) -> bool: """Whether this object is an `__init__.py` module. - See also: [`is_module`][griffe.Object.is_module]. + See also: [`is_module`][griffelib.Object.is_module]. """ return False @@ -923,7 +937,7 @@ def is_init_module(self) -> bool: def is_package(self) -> bool: """Whether this object is a package (top module). - See also: [`is_subpackage`][griffe.Object.is_subpackage]. + See also: [`is_subpackage`][griffelib.Object.is_subpackage]. """ return False @@ -931,7 +945,7 @@ def is_package(self) -> bool: def is_subpackage(self) -> bool: """Whether this object is a subpackage. - See also: [`is_package`][griffe.Object.is_package]. + See also: [`is_package`][griffelib.Object.is_package]. """ return False @@ -939,7 +953,7 @@ def is_subpackage(self) -> bool: def is_namespace_package(self) -> bool: """Whether this object is a namespace package (top folder, no `__init__.py`). - See also: [`is_namespace_subpackage`][griffe.Object.is_namespace_subpackage]. + See also: [`is_namespace_subpackage`][griffelib.Object.is_namespace_subpackage]. """ return False @@ -947,14 +961,14 @@ def is_namespace_package(self) -> bool: def is_namespace_subpackage(self) -> bool: """Whether this object is a namespace subpackage. - See also: [`is_namespace_package`][griffe.Object.is_namespace_package]. + See also: [`is_namespace_package`][griffelib.Object.is_namespace_package]. """ return False def has_labels(self, *labels: str) -> bool: """Tell if this object has all the given labels. - See also: [`labels`][griffe.Object.labels]. + See also: [`labels`][griffelib.Object.labels]. Parameters: *labels: Labels that must be present. @@ -967,7 +981,7 @@ def has_labels(self, *labels: str) -> bool: def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]: """Filter and return members based on predicates. - See also: [`members`][griffe.Object.members]. + See also: [`members`][griffelib.Object.members]. Parameters: *predicates: A list of predicates, i.e. callables accepting a member as argument and returning a boolean. @@ -986,7 +1000,7 @@ def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[ def module(self) -> Module: """The parent module of this object. - See also: [`package`][griffe.Object.package]. + See also: [`package`][griffelib.Object.package]. Examples: >>> import griffelib @@ -1010,7 +1024,7 @@ def module(self) -> Module: def package(self) -> Module: """The absolute top module (the package) of this object. - See also: [`module`][griffe.Object.module]. + See also: [`module`][griffelib.Object.module]. Examples: >>> import griffelib @@ -1027,8 +1041,8 @@ def package(self) -> Module: def filepath(self) -> Path | list[Path]: """The file path (or directory list for namespace packages) where this object was defined. - See also: [`relative_filepath`][griffe.Object.relative_filepath], - [`relative_package_filepath`][griffe.Object.relative_package_filepath]. + See also: [`relative_filepath`][griffelib.Object.relative_filepath], + [`relative_package_filepath`][griffelib.Object.relative_package_filepath]. Examples: >>> import griffelib @@ -1042,8 +1056,8 @@ def filepath(self) -> Path | list[Path]: def relative_package_filepath(self) -> Path: """The file path where this object was defined, relative to the top module path. - See also: [`filepath`][griffe.Object.filepath], - [`relative_filepath`][griffe.Object.relative_filepath]. + See also: [`filepath`][griffelib.Object.filepath], + [`relative_filepath`][griffelib.Object.relative_filepath]. Raises: ValueError: When the relative path could not be computed. @@ -1088,8 +1102,8 @@ def relative_filepath(self) -> Path: If this object's file path is not relative to the current working directory, return its absolute path. - See also: [`filepath`][griffe.Object.filepath], - [`relative_package_filepath`][griffe.Object.relative_package_filepath]. + See also: [`filepath`][griffelib.Object.filepath], + [`relative_package_filepath`][griffelib.Object.relative_package_filepath]. Raises: ValueError: When the relative path could not be computed. @@ -1111,7 +1125,7 @@ def path(self) -> str: On regular objects (not aliases), the path is the canonical path. - See also: [`canonical_path`][griffe.Object.canonical_path]. + See also: [`canonical_path`][griffelib.Object.canonical_path]. Examples: >>> import griffelib @@ -1127,7 +1141,7 @@ def canonical_path(self) -> str: The canonical path is the path where the object was defined (not imported). - See also: [`path`][griffe.Object.path]. + See also: [`path`][griffelib.Object.path]. """ if self.parent is None: return self.name @@ -1150,8 +1164,8 @@ def modules_collection(self) -> ModulesCollection: def lines_collection(self) -> LinesCollection: """The lines collection attached to this object or its parents. - See also: [`lines`][griffe.Object.lines], - [`source`][griffe.Object.source]. + See also: [`lines`][griffelib.Object.lines], + [`source`][griffelib.Object.source]. Raises: ValueError: When no modules collection can be found in the object or its parents. @@ -1166,8 +1180,8 @@ def lines_collection(self) -> LinesCollection: def lines(self) -> list[str]: """The lines containing the source of this object. - See also: [`lines_collection`][griffe.Object.lines_collection], - [`source`][griffe.Object.source]. + See also: [`lines_collection`][griffelib.Object.lines_collection], + [`source`][griffelib.Object.source]. """ try: filepath = self.filepath @@ -1189,8 +1203,8 @@ def lines(self) -> list[str]: def source(self) -> str: """The source code of this object. - See also: [`lines`][griffe.Object.lines], - [`lines_collection`][griffe.Object.lines_collection]. + See also: [`lines`][griffelib.Object.lines], + [`lines_collection`][griffelib.Object.lines_collection]. """ return dedent("\n".join(self.lines)) @@ -1240,7 +1254,7 @@ def resolve(self, name: str) -> str: def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]: """Return this object's data as a dictionary. - See also: [`as_json`][griffe.Object.as_json]. + See also: [`as_json`][griffelib.Object.as_json]. Parameters: full: Whether to return full info, or just base info. @@ -1336,7 +1350,7 @@ class Alias(ObjectAliasMixin): - the path is the alias path, not the canonical one - the name can be different from the target's - if the target can be resolved, the kind is the target's kind - - if the target cannot be resolved, the kind becomes [Kind.ALIAS][griffe.Kind] + - if the target cannot be resolved, the kind becomes [Kind.ALIAS][griffelib.Kind] """ is_alias: bool = True @@ -1344,7 +1358,7 @@ class Alias(ObjectAliasMixin): is_collection: bool = False """Always false for aliases. - See also: [`ModulesCollection`][griffe.ModulesCollection]. + See also: [`ModulesCollection`][griffelib.ModulesCollection]. """ def __init__( @@ -1439,7 +1453,7 @@ def __len__(self) -> int: def kind(self) -> Kind: """The target's kind, or `Kind.ALIAS` if the target cannot be resolved. - See also: [`is_kind`][griffe.Alias.is_kind]. + See also: [`is_kind`][griffelib.Alias.is_kind]. """ # custom behavior to avoid raising exceptions try: @@ -1451,8 +1465,8 @@ def kind(self) -> Kind: def has_docstring(self) -> bool: """Whether this alias' target has a non-empty docstring. - See also: [`has_docstrings`][griffe.Alias.has_docstrings], - [`docstring`][griffe.Alias.docstring]. + See also: [`has_docstrings`][griffelib.Alias.has_docstrings], + [`docstring`][griffelib.Alias.docstring]. """ try: return self.final_target.has_docstring @@ -1463,8 +1477,8 @@ def has_docstring(self) -> bool: def has_docstrings(self) -> bool: """Whether this alias' target or any of its members has a non-empty docstring. - See also: [`has_docstring`][griffe.Alias.has_docstring], - [`docstring`][griffe.Alias.docstring]. + See also: [`has_docstring`][griffelib.Alias.has_docstring], + [`docstring`][griffelib.Alias.docstring]. """ try: return self.final_target.has_docstrings @@ -1485,7 +1499,7 @@ def parent(self, value: Module | Class | Alias) -> None: def path(self) -> str: """The dotted path / import path of this object. - See also: [`canonical_path`][griffe.Alias.canonical_path]. + See also: [`canonical_path`][griffelib.Alias.canonical_path]. """ return f"{self.parent.path}.{self.name}" # type: ignore[union-attr] @@ -1499,10 +1513,10 @@ def modules_collection(self) -> ModulesCollection: def members(self) -> dict[str, Object | Alias]: """The target's members (modules, classes, functions, attributes, type aliases). - See also: [`inherited_members`][griffe.Alias.inherited_members], - [`get_member`][griffe.Alias.get_member], - [`set_member`][griffe.Alias.set_member], - [`filter_members`][griffe.Alias.filter_members]. + See also: [`inherited_members`][griffelib.Alias.inherited_members], + [`get_member`][griffelib.Alias.get_member], + [`set_member`][griffelib.Alias.set_member], + [`filter_members`][griffelib.Alias.filter_members]. """ final_target = self.final_target @@ -1525,7 +1539,7 @@ def inherited_members(self) -> dict[str, Alias]: This method is part of the consumer API: do not use when producing Griffe trees! - See also: [`members`][griffe.Alias.members]. + See also: [`members`][griffelib.Alias.members]. """ final_target = self.final_target @@ -1541,7 +1555,7 @@ def inherited_members(self) -> dict[str, Alias]: def as_json(self, *, full: bool = False, **kwargs: Any) -> str: """Return this target's data as a JSON string. - See also: [`as_dict`][griffe.Alias.as_dict]. + See also: [`as_dict`][griffelib.Alias.as_dict]. Parameters: full: Whether to return full info, or just base info. @@ -1589,7 +1603,7 @@ def extra(self) -> dict: def lineno(self) -> int | None: """The starting line number of the target object. - See also: [`endlineno`][griffe.Alias.endlineno]. + See also: [`endlineno`][griffelib.Alias.endlineno]. """ return self.final_target.lineno @@ -1601,7 +1615,7 @@ def lineno(self, lineno: int | None) -> None: def endlineno(self) -> int | None: """The ending line number of the target object. - See also: [`lineno`][griffe.Alias.lineno]. + See also: [`lineno`][griffelib.Alias.lineno]. """ return self.final_target.endlineno @@ -1613,8 +1627,8 @@ def endlineno(self, endlineno: int | None) -> None: def docstring(self) -> Docstring | None: """The target docstring. - See also: [`has_docstring`][griffe.Alias.has_docstring], - [`has_docstrings`][griffe.Alias.has_docstrings]. + See also: [`has_docstring`][griffelib.Alias.has_docstring], + [`has_docstrings`][griffelib.Alias.has_docstrings]. """ return self.final_target.docstring @@ -1631,7 +1645,7 @@ def type_parameters(self) -> TypeParameters: def labels(self) -> set[str]: """The target labels (`property`, `dataclass`, etc.). - See also: [`has_labels`][griffe.Alias.has_labels]. + See also: [`has_labels`][griffelib.Alias.has_labels]. """ return self.final_target.labels @@ -1642,7 +1656,7 @@ def imports(self) -> dict[str, str]: Keys are the names within the object (`from ... import ... as AS_NAME`), while the values are the actual names of the objects (`from ... import REAL_NAME as ...`). - See also: [`is_imported`][griffe.Alias.is_imported]. + See also: [`is_imported`][griffelib.Alias.is_imported]. """ return self.final_target.imports @@ -1661,7 +1675,7 @@ def exports(self) -> list[str | ExprName] | None: Exports get expanded by the loader before it expands wildcards and resolves aliases. - See also: [`GriffeLoader.expand_exports`][griffe.GriffeLoader.expand_exports]. + See also: [`GriffeLoader.expand_exports`][griffelib.GriffeLoader.expand_exports]. """ return self.final_target.exports @@ -1673,12 +1687,12 @@ def aliases(self) -> dict[str, Alias]: def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool: """Tell if this object is of the given kind. - See also: [`is_module`][griffe.Alias.is_module], - [`is_class`][griffe.Alias.is_class], - [`is_function`][griffe.Alias.is_function], - [`is_attribute`][griffe.Alias.is_attribute], - [`is_type_alias`][griffe.Alias.is_type_alias], - [`is_alias`][griffe.Alias.is_alias]. + See also: [`is_module`][griffelib.Alias.is_module], + [`is_class`][griffelib.Alias.is_class], + [`is_function`][griffelib.Alias.is_function], + [`is_attribute`][griffelib.Alias.is_attribute], + [`is_type_alias`][griffelib.Alias.is_type_alias], + [`is_alias`][griffelib.Alias.is_alias]. Parameters: kind: An instance or set of kinds (strings or enumerations). @@ -1695,13 +1709,13 @@ def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool: def is_module(self) -> bool: """Whether this object is a module. - See also: [`is_init_module`][griffe.Alias.is_init_module]. - [`is_class`][griffe.Alias.is_class], - [`is_function`][griffe.Alias.is_function], - [`is_attribute`][griffe.Alias.is_attribute], - [`is_type_alias`][griffe.Alias.is_type_alias], - [`is_alias`][griffe.Alias.is_alias], - [`is_kind`][griffe.Alias.is_kind]. + See also: [`is_init_module`][griffelib.Alias.is_init_module]. + [`is_class`][griffelib.Alias.is_class], + [`is_function`][griffelib.Alias.is_function], + [`is_attribute`][griffelib.Alias.is_attribute], + [`is_type_alias`][griffelib.Alias.is_type_alias], + [`is_alias`][griffelib.Alias.is_alias], + [`is_kind`][griffelib.Alias.is_kind]. """ return self.final_target.is_module @@ -1709,12 +1723,12 @@ def is_module(self) -> bool: def is_class(self) -> bool: """Whether this object is a class. - See also: [`is_module`][griffe.Alias.is_module], - [`is_function`][griffe.Alias.is_function], - [`is_attribute`][griffe.Alias.is_attribute], - [`is_type_alias`][griffe.Alias.is_type_alias], - [`is_alias`][griffe.Alias.is_alias], - [`is_kind`][griffe.Alias.is_kind]. + See also: [`is_module`][griffelib.Alias.is_module], + [`is_function`][griffelib.Alias.is_function], + [`is_attribute`][griffelib.Alias.is_attribute], + [`is_type_alias`][griffelib.Alias.is_type_alias], + [`is_alias`][griffelib.Alias.is_alias], + [`is_kind`][griffelib.Alias.is_kind]. """ return self.final_target.is_class @@ -1722,12 +1736,12 @@ def is_class(self) -> bool: def is_function(self) -> bool: """Whether this object is a function. - See also: [`is_module`][griffe.Alias.is_module], - [`is_class`][griffe.Alias.is_class], - [`is_attribute`][griffe.Alias.is_attribute], - [`is_type_alias`][griffe.Alias.is_type_alias], - [`is_alias`][griffe.Alias.is_alias], - [`is_kind`][griffe.Alias.is_kind]. + See also: [`is_module`][griffelib.Alias.is_module], + [`is_class`][griffelib.Alias.is_class], + [`is_attribute`][griffelib.Alias.is_attribute], + [`is_type_alias`][griffelib.Alias.is_type_alias], + [`is_alias`][griffelib.Alias.is_alias], + [`is_kind`][griffelib.Alias.is_kind]. """ return self.final_target.is_function @@ -1735,12 +1749,12 @@ def is_function(self) -> bool: def is_attribute(self) -> bool: """Whether this object is an attribute. - See also: [`is_module`][griffe.Alias.is_module], - [`is_class`][griffe.Alias.is_class], - [`is_function`][griffe.Alias.is_function], - [`is_type_alias`][griffe.Alias.is_type_alias], - [`is_alias`][griffe.Alias.is_alias], - [`is_kind`][griffe.Alias.is_kind]. + See also: [`is_module`][griffelib.Alias.is_module], + [`is_class`][griffelib.Alias.is_class], + [`is_function`][griffelib.Alias.is_function], + [`is_type_alias`][griffelib.Alias.is_type_alias], + [`is_alias`][griffelib.Alias.is_alias], + [`is_kind`][griffelib.Alias.is_kind]. """ return self.final_target.is_attribute @@ -1748,19 +1762,19 @@ def is_attribute(self) -> bool: def is_type_alias(self) -> bool: """Whether this object is a type alias. - See also: [`is_module`][griffe.Alias.is_module], - [`is_class`][griffe.Alias.is_class], - [`is_function`][griffe.Alias.is_function], - [`is_attribute`][griffe.Alias.is_attribute], - [`is_alias`][griffe.Alias.is_alias], - [`is_kind`][griffe.Alias.is_kind]. + See also: [`is_module`][griffelib.Alias.is_module], + [`is_class`][griffelib.Alias.is_class], + [`is_function`][griffelib.Alias.is_function], + [`is_attribute`][griffelib.Alias.is_attribute], + [`is_alias`][griffelib.Alias.is_alias], + [`is_kind`][griffelib.Alias.is_kind]. """ return self.final_target.is_type_alias def has_labels(self, *labels: str) -> bool: """Tell if this object has all the given labels. - See also: [`labels`][griffe.Alias.labels]. + See also: [`labels`][griffelib.Alias.labels]. Parameters: *labels: Labels that must be present. @@ -1773,9 +1787,9 @@ def has_labels(self, *labels: str) -> bool: def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]: """Filter and return members based on predicates. - See also: [`members`][griffe.Alias.members], - [`get_member`][griffe.Alias.get_member], - [`set_member`][griffe.Alias.set_member]. + See also: [`members`][griffelib.Alias.members], + [`get_member`][griffelib.Alias.get_member], + [`set_member`][griffelib.Alias.set_member]. Parameters: *predicates: A list of predicates, i.e. callables accepting a member as argument and returning a boolean. @@ -1789,7 +1803,7 @@ def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[ def module(self) -> Module: """The parent module of this object. - See also: [`package`][griffe.Alias.package]. + See also: [`package`][griffelib.Alias.package]. Raises: ValueError: When the object is not a module and does not have a parent. @@ -1800,7 +1814,7 @@ def module(self) -> Module: def package(self) -> Module: """The absolute top module (the package) of this object. - See also: [`module`][griffe.Alias.module]. + See also: [`module`][griffelib.Alias.module]. """ return self.final_target.package @@ -1808,8 +1822,8 @@ def package(self) -> Module: def filepath(self) -> Path | list[Path]: """The file path (or directory list for namespace packages) where this object was defined. - See also: [`relative_filepath`][griffe.Alias.relative_filepath], - [`relative_package_filepath`][griffe.Alias.relative_package_filepath]. + See also: [`relative_filepath`][griffelib.Alias.relative_filepath], + [`relative_package_filepath`][griffelib.Alias.relative_package_filepath]. """ return self.final_target.filepath @@ -1819,8 +1833,8 @@ def relative_filepath(self) -> Path: If this object's file path is not relative to the current working directory, return its absolute path. - See also: [`filepath`][griffe.Alias.filepath], - [`relative_package_filepath`][griffe.Alias.relative_package_filepath]. + See also: [`filepath`][griffelib.Alias.filepath], + [`relative_package_filepath`][griffelib.Alias.relative_package_filepath]. Raises: ValueError: When the relative path could not be computed. @@ -1831,8 +1845,8 @@ def relative_filepath(self) -> Path: def relative_package_filepath(self) -> Path: """The file path where this object was defined, relative to the top module path. - See also: [`filepath`][griffe.Alias.filepath], - [`relative_filepath`][griffe.Alias.relative_filepath]. + See also: [`filepath`][griffelib.Alias.filepath], + [`relative_filepath`][griffelib.Alias.relative_filepath]. Raises: ValueError: When the relative path could not be computed. @@ -1845,7 +1859,7 @@ def canonical_path(self) -> str: The canonical path is the path where the object was defined (not imported). - See also: [`path`][griffe.Alias.path]. + See also: [`path`][griffelib.Alias.path]. """ return self.final_target.canonical_path @@ -1853,8 +1867,8 @@ def canonical_path(self) -> str: def lines_collection(self) -> LinesCollection: """The lines collection attached to this object or its parents. - See also: [`lines`][griffe.Alias.lines], - [`source`][griffe.Alias.source]. + See also: [`lines`][griffelib.Alias.lines], + [`source`][griffelib.Alias.source]. Raises: ValueError: When no modules collection can be found in the object or its parents. @@ -1865,8 +1879,8 @@ def lines_collection(self) -> LinesCollection: def lines(self) -> list[str]: """The lines containing the source of this object. - See also: [`source`][griffe.Alias.source], - [`lines_collection`][griffe.Alias.lines_collection]. + See also: [`source`][griffelib.Alias.source], + [`lines_collection`][griffelib.Alias.lines_collection]. """ return self.final_target.lines @@ -1874,8 +1888,8 @@ def lines(self) -> list[str]: def source(self) -> str: """The source code of this object. - See also: [`lines`][griffe.Alias.lines], - [`lines_collection`][griffe.Alias.lines_collection]. + See also: [`lines`][griffelib.Alias.lines], + [`lines_collection`][griffelib.Alias.lines_collection]. """ return self.final_target.source @@ -1906,9 +1920,9 @@ def _filepath(self) -> Path | list[Path] | None: def bases(self) -> list[Expr | str]: """The class bases. - See also: [`Class`][griffe.Class], - [`resolved_bases`][griffe.Alias.resolved_bases], - [`mro`][griffe.Alias.mro]. + See also: [`Class`][griffelib.Class], + [`resolved_bases`][griffelib.Alias.resolved_bases], + [`mro`][griffelib.Alias.mro]. """ return cast("Class", self.final_target).bases @@ -1921,8 +1935,8 @@ def keywords(self) -> dict[str, Expr | str]: def decorators(self) -> list[Decorator]: """The class/function decorators. - See also: [`Function`][griffe.Function], - [`Class`][griffe.Class]. + See also: [`Function`][griffelib.Function], + [`Class`][griffelib.Class]. """ return cast("Union[Class, Function]", self.target).decorators @@ -1940,7 +1954,7 @@ def is_init_method(self) -> bool: def is_init_module(self) -> bool: """Whether this module is an `__init__.py` module. - See also: [`is_module`][griffe.Alias.is_module]. + See also: [`is_module`][griffelib.Alias.is_module]. """ return cast("Module", self.final_target).is_init_module @@ -1948,7 +1962,7 @@ def is_init_module(self) -> bool: def is_package(self) -> bool: """Whether this module is a package (top module). - See also: [`is_subpackage`][griffe.Alias.is_subpackage]. + See also: [`is_subpackage`][griffelib.Alias.is_subpackage]. """ return cast("Module", self.final_target).is_package @@ -1956,7 +1970,7 @@ def is_package(self) -> bool: def is_subpackage(self) -> bool: """Whether this module is a subpackage. - See also: [`is_package`][griffe.Alias.is_package]. + See also: [`is_package`][griffelib.Alias.is_package]. """ return cast("Module", self.final_target).is_subpackage @@ -1964,7 +1978,7 @@ def is_subpackage(self) -> bool: def is_namespace_package(self) -> bool: """Whether this module is a namespace package (top folder, no `__init__.py`). - See also: [`is_namespace_subpackage`][griffe.Alias.is_namespace_subpackage]. + See also: [`is_namespace_subpackage`][griffelib.Alias.is_namespace_subpackage]. """ return cast("Module", self.final_target).is_namespace_package @@ -1972,7 +1986,7 @@ def is_namespace_package(self) -> bool: def is_namespace_subpackage(self) -> bool: """Whether this module is a namespace subpackage. - See also: [`is_namespace_package`][griffe.Alias.is_namespace_package]. + See also: [`is_namespace_package`][griffelib.Alias.is_namespace_package]. """ return cast("Module", self.final_target).is_namespace_subpackage @@ -2068,9 +2082,9 @@ def target(self) -> Object | Alias: Upon accessing this property, if the target is not already resolved, a lookup is done using the modules collection to find the target. - See also: [`final_target`][griffe.Alias.final_target], - [`resolve_target`][griffe.Alias.resolve_target], - [`resolved`][griffe.Alias.resolved]. + See also: [`final_target`][griffelib.Alias.final_target], + [`resolve_target`][griffelib.Alias.resolve_target], + [`resolved`][griffelib.Alias.resolved]. """ if not self.resolved: self.resolve_target() @@ -2091,9 +2105,9 @@ def final_target(self) -> Object: This will iterate through the targets until a non-alias object is found. - See also: [`target`][griffe.Alias.target], - [`resolve_target`][griffe.Alias.resolve_target], - [`resolved`][griffe.Alias.resolved]. + See also: [`target`][griffelib.Alias.target], + [`resolve_target`][griffelib.Alias.resolve_target], + [`resolved`][griffelib.Alias.resolved]. """ # Here we quickly iterate on the alias chain, # remembering which path we've seen already to detect cycles. @@ -2114,9 +2128,9 @@ def final_target(self) -> Object: def resolve_target(self) -> None: """Resolve the target. - See also: [`target`][griffe.Alias.target], - [`final_target`][griffe.Alias.final_target], - [`resolved`][griffe.Alias.resolved]. + See also: [`target`][griffelib.Alias.target], + [`final_target`][griffelib.Alias.final_target], + [`resolved`][griffelib.Alias.resolved]. Raises: AliasResolutionError: When the target cannot be resolved. @@ -2173,7 +2187,7 @@ def resolved(self) -> bool: def wildcard(self) -> str | None: """The module on which the wildcard import is performed (if any). - See also: [`GriffeLoader.expand_wildcards`][griffe.GriffeLoader.expand_wildcards]. + See also: [`GriffeLoader.expand_wildcards`][griffelib.GriffeLoader.expand_wildcards]. """ if self.name.endswith("/*"): return self.target_path @@ -2182,7 +2196,7 @@ def wildcard(self) -> str | None: def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]: # noqa: ARG002 """Return this alias' data as a dictionary. - See also: [`as_json`][griffe.Alias.as_json]. + See also: [`as_json`][griffelib.Alias.as_json]. Parameters: full: Whether to return full info, or just base info. @@ -2276,7 +2290,7 @@ def imports_future_annotations(self) -> bool: def is_init_module(self) -> bool: """Whether this module is an `__init__.py` module. - See also: [`is_module`][griffe.Module.is_module]. + See also: [`is_module`][griffelib.Module.is_module]. """ if isinstance(self.filepath, list): return False @@ -2289,7 +2303,7 @@ def is_init_module(self) -> bool: def is_package(self) -> bool: """Whether this module is a package (top module). - See also: [`is_subpackage`][griffe.Module.is_subpackage]. + See also: [`is_subpackage`][griffelib.Module.is_subpackage]. """ return not bool(self.parent) and self.is_init_module @@ -2297,7 +2311,7 @@ def is_package(self) -> bool: def is_subpackage(self) -> bool: """Whether this module is a subpackage. - See also: [`is_package`][griffe.Module.is_package]. + See also: [`is_package`][griffelib.Module.is_package]. """ return bool(self.parent) and self.is_init_module @@ -2305,7 +2319,7 @@ def is_subpackage(self) -> bool: def is_namespace_package(self) -> bool: """Whether this module is a namespace package (top folder, no `__init__.py`). - See also: [`is_namespace_subpackage`][griffe.Module.is_namespace_subpackage]. + See also: [`is_namespace_subpackage`][griffelib.Module.is_namespace_subpackage]. """ try: return self.parent is None and isinstance(self.filepath, list) @@ -2316,7 +2330,7 @@ def is_namespace_package(self) -> bool: def is_namespace_subpackage(self) -> bool: """Whether this module is a namespace subpackage. - See also: [`is_namespace_package`][griffe.Module.is_namespace_package]. + See also: [`is_namespace_package`][griffelib.Module.is_namespace_package]. """ try: return ( @@ -2333,7 +2347,7 @@ def is_namespace_subpackage(self) -> bool: def as_dict(self, **kwargs: Any) -> dict[str, Any]: """Return this module's data as a dictionary. - See also: [`as_json`][griffe.Module.as_json]. + See also: [`as_json`][griffelib.Module.as_json]. Parameters: **kwargs: Additional serialization options. @@ -2378,8 +2392,8 @@ def __init__( self.bases: list[Expr | str] = list(bases) if bases else [] """The class bases. - See also: [`resolved_bases`][griffe.Class.resolved_bases], - [`mro`][griffe.Class.mro]. + See also: [`resolved_bases`][griffelib.Class.resolved_bases], + [`mro`][griffelib.Class.mro]. """ self.decorators: list[Decorator] = decorators or [] @@ -2428,8 +2442,8 @@ def resolved_bases(self) -> list[Object]: This method is part of the consumer API: do not use when producing Griffe trees! - See also: [`bases`][griffe.Class.bases], - [`mro`][griffe.Class.mro]. + See also: [`bases`][griffelib.Class.bases], + [`mro`][griffelib.Class.mro]. """ resolved_bases = [] for base in self.bases: @@ -2458,15 +2472,15 @@ def _mro(self, seen: tuple[str, ...] = ()) -> list[Class]: def mro(self) -> list[Class]: """Return a list of classes in order corresponding to Python's MRO. - See also: [`bases`][griffe.Class.bases], - [`resolved_bases`][griffe.Class.resolved_bases]. + See also: [`bases`][griffelib.Class.bases], + [`resolved_bases`][griffelib.Class.resolved_bases]. """ return self._mro()[1:] # Remove self. def as_dict(self, **kwargs: Any) -> dict[str, Any]: """Return this class' data as a dictionary. - See also: [`as_json`][griffe.Class.as_json]. + See also: [`as_json`][griffelib.Class.as_json]. Parameters: **kwargs: Additional serialization options. @@ -2561,7 +2575,7 @@ def is_init_method(self) -> bool: def as_dict(self, **kwargs: Any) -> dict[str, Any]: """Return this function's data as a dictionary. - See also: [`as_json`][griffe.Function.as_json]. + See also: [`as_json`][griffelib.Function.as_json]. Parameters: **kwargs: Additional serialization options. @@ -2683,7 +2697,7 @@ def __init__( def as_dict(self, **kwargs: Any) -> dict[str, Any]: """Return this attribute's data as a dictionary. - See also: [`as_json`][griffe.Attribute.as_json]. + See also: [`as_json`][griffelib.Attribute.as_json]. Parameters: **kwargs: Additional serialization options. diff --git a/tests/test_api.py b/tests/test_api.py index 64450cc81..afe12e255 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -32,7 +32,7 @@ def _fixture_loader() -> griffelib.GriffeLoader: @pytest.fixture(name="internal_api", scope="module") def _fixture_internal_api(loader: griffelib.GriffeLoader) -> griffelib.Module: - return loader.modules_collection["griffe._internal"] + return loader.modules_collection["griffelib._internal"] @pytest.fixture(name="public_api", scope="module") @@ -47,7 +47,7 @@ def _yield_public_objects( modulelevel: bool = True, inherited: bool = False, special: bool = False, -) -> Iterator[griffe.Object | griffelib.Alias]: +) -> Iterator[griffelib.Object | griffelib.Alias]: for member in obj.all_members.values() if inherited else obj.members.values(): try: if member.is_module: @@ -78,17 +78,23 @@ def _yield_public_objects( @pytest.fixture(name="modulelevel_internal_objects", scope="module") -def _fixture_modulelevel_internal_objects(internal_api: griffelib.Module) -> list[griffe.Object | griffelib.Alias]: +def _fixture_modulelevel_internal_objects( + internal_api: griffelib.Module, +) -> list[griffelib.Object | griffelib.Alias]: return list(_yield_public_objects(internal_api, modulelevel=True)) @pytest.fixture(name="internal_objects", scope="module") -def _fixture_internal_objects(internal_api: griffelib.Module) -> list[griffe.Object | griffelib.Alias]: +def _fixture_internal_objects( + internal_api: griffelib.Module, +) -> list[griffelib.Object | griffelib.Alias]: return list(_yield_public_objects(internal_api, modulelevel=False, special=True)) @pytest.fixture(name="public_objects", scope="module") -def _fixture_public_objects(public_api: griffelib.Module) -> list[griffe.Object | griffelib.Alias]: +def _fixture_public_objects( + public_api: griffelib.Module, +) -> list[griffelib.Object | griffelib.Alias]: return list(_yield_public_objects(public_api, modulelevel=False, inherited=True, special=True)) @@ -115,7 +121,9 @@ def test_alias_proxies(internal_api: griffelib.Module) -> None: assert name in alias_members -def test_exposed_objects(modulelevel_internal_objects: list[griffe.Object | griffelib.Alias]) -> None: +def test_exposed_objects( + modulelevel_internal_objects: list[griffelib.Object | griffelib.Alias], +) -> None: """All public objects in the internal API are exposed under `griffe`.""" not_exposed = [ obj.path @@ -125,7 +133,9 @@ def test_exposed_objects(modulelevel_internal_objects: list[griffe.Object | grif assert not not_exposed, "Objects not exposed:\n" + "\n".join(sorted(not_exposed)) -def test_unique_names(modulelevel_internal_objects: list[griffe.Object | griffelib.Alias]) -> None: +def test_unique_names( + modulelevel_internal_objects: list[griffelib.Object | griffelib.Alias], +) -> None: """All internal objects have unique names.""" names_to_paths = defaultdict(list) for obj in modulelevel_internal_objects: @@ -152,7 +162,9 @@ def _public_path(obj: griffelib.Object | griffelib.Alias) -> bool: ) -def test_api_matches_inventory(inventory: Inventory, public_objects: list[griffe.Object | griffelib.Alias]) -> None: +def test_api_matches_inventory( + inventory: Inventory, public_objects: list[griffelib.Object | griffelib.Alias] +) -> None: """All public objects are added to the inventory.""" ignore_names = {"__getattr__", "__init__", "__repr__", "__str__", "__post_init__"} ignore_paths = {"griffe.DataclassesExtension.*", "griffe.UnpackTypedDictExtension.*"} @@ -171,7 +183,7 @@ def test_api_matches_inventory(inventory: Inventory, public_objects: list[griffe def test_inventory_matches_api( inventory: Inventory, - public_objects: list[griffe.Object | griffelib.Alias], + public_objects: list[griffelib.Object | griffelib.Alias], loader: griffelib.GriffeLoader, ) -> None: """The inventory doesn't contain any additional Python object.""" @@ -194,7 +206,7 @@ def test_no_module_docstrings_in_internal_api(internal_api: griffelib.Module) -> but internal modules are not exposed to users, so they should not have docstrings. """ - def _modules(obj: griffelib.Module) -> Iterator[griffe.Module]: + def _modules(obj: griffelib.Module) -> Iterator[griffelib.Module]: for member in obj.modules.values(): yield member yield from _modules(member) diff --git a/tests/test_docstrings/test_google.py b/tests/test_docstrings/test_google.py index 828121357..20b639e81 100644 --- a/tests/test_docstrings/test_google.py +++ b/tests/test_docstrings/test_google.py @@ -1,4 +1,4 @@ -"""Tests for the [Google-style parser][griffe.docstrings.google].""" +"""Tests for the [Google-style parser][griffelib.docstrings.google].""" from __future__ import annotations diff --git a/tests/test_docstrings/test_numpy.py b/tests/test_docstrings/test_numpy.py index 08651c897..3e95b70dd 100644 --- a/tests/test_docstrings/test_numpy.py +++ b/tests/test_docstrings/test_numpy.py @@ -1,4 +1,4 @@ -"""Tests for the [Numpy-style parser][griffe.docstrings.numpy].""" +"""Tests for the [Numpy-style parser][griffelib.docstrings.numpy].""" from __future__ import annotations diff --git a/tests/test_docstrings/test_sphinx.py b/tests/test_docstrings/test_sphinx.py index 5e4af02a3..fe4f9f2f7 100644 --- a/tests/test_docstrings/test_sphinx.py +++ b/tests/test_docstrings/test_sphinx.py @@ -1,4 +1,4 @@ -"""Tests for the [Sphinx-style parser][griffe.docstrings.sphinx].""" +"""Tests for the [Sphinx-style parser][griffelib.docstrings.sphinx].""" from __future__ import annotations From 7cc4ea44190821b4220bd6e4e8ce42df282d9c7f Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 16:23:35 +0100 Subject: [PATCH 09/10] Simplify griffecli's `__main__` --- packages/griffecli/src/griffecli/__main__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/griffecli/src/griffecli/__main__.py b/packages/griffecli/src/griffecli/__main__.py index 0bd485571..f5e0f8f1d 100644 --- a/packages/griffecli/src/griffecli/__main__.py +++ b/packages/griffecli/src/griffecli/__main__.py @@ -7,7 +7,7 @@ import sys -from griffecli._internal.cli import main +from griffecli import main if __name__ == "__main__": sys.exit(main(sys.argv[1:])) From 457fdb20a54bc6c1509b5b311fa1881aa53eda5a Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sat, 29 Nov 2025 16:29:42 +0100 Subject: [PATCH 10/10] Bump maj --- docs/guide/contributors/workflow.md | 4 -- docs/reference/api/agents.md | 4 -- docs/reference/api/git.md | 13 ---- duties.py | 2 - mkdocs.yml | 4 -- .../src/griffecli/_internal/__init__.py | 0 packages/griffelib/src/griffelib/__init__.py | 31 -------- .../_internal/agents/nodes/exports.py | 12 ---- .../griffelib/_internal/docstrings/auto.py | 22 +----- .../griffelib/_internal/docstrings/google.py | 5 -- .../griffelib/_internal/docstrings/numpy.py | 5 -- .../griffelib/_internal/docstrings/sphinx.py | 5 -- .../src/griffelib/_internal/encoders.py | 12 +--- .../griffelib/_internal/extensions/base.py | 41 +---------- .../griffelib/src/griffelib/_internal/git.py | 2 +- .../src/griffelib/_internal/loader.py | 2 - scripts/griffe_exts.py | 24 ------- tests/test_api.py | 2 - tests/test_extensions/test_base.py | 70 ------------------- 19 files changed, 6 insertions(+), 254 deletions(-) delete mode 100644 docs/reference/api/git.md create mode 100644 packages/griffecli/src/griffecli/_internal/__init__.py delete mode 100644 scripts/griffe_exts.py diff --git a/docs/guide/contributors/workflow.md b/docs/guide/contributors/workflow.md index 0e6064a49..62d2ff5f4 100644 --- a/docs/guide/contributors/workflow.md +++ b/docs/guide/contributors/workflow.md @@ -57,10 +57,6 @@ Deprecated code should also be marked as legacy code. We use [Yore](https://pawa Examples: ```python title="Remove function when we bump to 2.0" -# YORE: Bump 2: Remove block. -def deprecated_function(): - ... -``` ```python title="Simplify imports when Python 3.15 is EOL" # YORE: EOL 3.15: Replace block with line 4. diff --git a/docs/reference/api/agents.md b/docs/reference/api/agents.md index 0a3d8c154..c4b78f9c9 100644 --- a/docs/reference/api/agents.md +++ b/docs/reference/api/agents.md @@ -70,8 +70,4 @@ Griffe is able to analyze code both statically and dynamically. ::: griffelib.safe_get_value - -## **Deprecated API** - -::: griffelib.ExportedName diff --git a/docs/reference/api/git.md b/docs/reference/api/git.md deleted file mode 100644 index 7abc81fcf..000000000 --- a/docs/reference/api/git.md +++ /dev/null @@ -1,13 +0,0 @@ -# Git utilities - - - -DANGER: **Deprecated utilities.** We have decided to stop exposing Git-related utilities as it's not a core part of the library's functionality. The functions documented on this page will become unavailable in the next major version. - -::: griffe.assert_git_repo - -::: griffe.get_latest_tag - -::: griffe.get_repo_root - -::: griffe.tmp_worktree diff --git a/duties.py b/duties.py index 2434398c8..ebd2086a8 100644 --- a/duties.py +++ b/duties.py @@ -291,8 +291,6 @@ def check_api(ctx: Context, *cli_args: str) -> None: color=True, extensions=[ "griffe_inherited_docstrings", - # YORE: Bump 2: Remove line. - "scripts/griffe_exts.py", "unpack_typeddict", ], ).add_args(*cli_args), diff --git a/mkdocs.yml b/mkdocs.yml index e9d7447e2..0ca192944 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -110,8 +110,6 @@ nav: - Parsers: reference/api/docstrings/parsers.md - Exceptions: reference/api/exceptions.md - Expressions: reference/api/expressions.md - # YORE: Bump 2: Remove line. - - Git utilities: reference/api/git.md - Loggers: reference/api/loggers.md - Helpers: reference/api/helpers.md - Changelog: changelog.md @@ -231,8 +229,6 @@ plugins: docstring_section_style: list extensions: - griffe_inherited_docstrings - # YORE: Bump 2: Remove line. - - scripts/griffe_exts.py - unpack_typeddict heading_level: 2 inherited_members: true diff --git a/packages/griffecli/src/griffecli/_internal/__init__.py b/packages/griffecli/src/griffecli/_internal/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/packages/griffelib/src/griffelib/__init__.py b/packages/griffelib/src/griffelib/__init__.py index 2fe136df4..71e59ee2f 100644 --- a/packages/griffelib/src/griffelib/__init__.py +++ b/packages/griffelib/src/griffelib/__init__.py @@ -186,7 +186,6 @@ ) from griffelib._internal.agents.nodes.docstrings import get_docstring -# YORE: Bump 2: Replace `ExportedName, ` with `` within line. from griffelib._internal.agents.nodes.exports import ( ExportedName, get__all__, @@ -405,30 +404,6 @@ vtree, ) -# YORE: Bump 2: Remove block. -_deprecated_names = ( - "assert_git_repo", - "get_latest_tag", - "get_repo_root", - "tmp_worktree", -) - - -# YORE: Bump 2: Remove block. -def __getattr__(name: str) -> Any: - if name in _deprecated_names: - from griffelib._internal import git # noqa: PLC0415 - - warnings.warn( - f"The `{name}` function is deprecated and will become unavailable in the next major version.", - DeprecationWarning, - stacklevel=2, - ) - return getattr(git, f"_{name}") - - raise AttributeError(f"module '{__name__}' has no attribute '{name}'") - - # Regenerate this list with the following Python snippet: # import griffelib # names = sorted(n for n in dir(griffe) if not n.startswith("_") and n not in ("Any", "annotations", "lazy_importing", "warnings")) @@ -489,8 +464,6 @@ def __getattr__(name: str) -> Any: "DocstringWarn", "DocstringYield", "ExplanationStyle", - # YORE: Bump 2: Remove line. - "ExportedName", "Expr", "ExprAttribute", "ExprBinOp", @@ -586,7 +559,6 @@ def __getattr__(name: str) -> Any: "UnimportableModuleError", "UnpackTypedDictExtension", "Visitor", - "assert_git_repo", "ast_children", "ast_first_child", "ast_kind", @@ -610,12 +582,10 @@ def __getattr__(name: str) -> Any: "get_docstring", "get_expression", "get_instance_names", - "get_latest_tag", "get_logger", "get_name", "get_names", "get_parameters", - "get_repo_root", "get_value", "htree", "infer_docstring_style", @@ -652,7 +622,6 @@ def __getattr__(name: str) -> Any: "temporary_pypackage", "temporary_visited_module", "temporary_visited_package", - "tmp_worktree", "typing_overload", "visit", "vtree", diff --git a/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py b/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py index 99fb18ddb..81e485e59 100644 --- a/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py +++ b/packages/griffelib/src/griffelib/_internal/agents/nodes/exports.py @@ -16,18 +16,6 @@ from griffelib._internal.models import Module -# YORE: Bump 2: Remove block. -@dataclass -class ExportedName: - """Deprecated. An intermediate class to store names. - - The [`get__all__`][griffelib.get__all__] function now returns instances of [`ExprName`][griffelib.ExprName] instead. - """ - - name: str - """The exported name.""" - parent: Module - """The parent module.""" def _extract_attribute(node: ast.Attribute, parent: Module) -> list[str | ExprName]: diff --git a/packages/griffelib/src/griffelib/_internal/docstrings/auto.py b/packages/griffelib/src/griffelib/_internal/docstrings/auto.py index ca2970f54..c27084d6d 100644 --- a/packages/griffelib/src/griffelib/_internal/docstrings/auto.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/auto.py @@ -121,8 +121,6 @@ def infer_docstring_style( style_order: list[Parser] | list[DocstringStyle] | None = None, default: Parser | DocstringStyle | None = None, per_style_options: PerStyleOptions | None = None, - # YORE: Bump 2: Remove line. - **options: Any, ) -> tuple[Parser | None, list[DocstringSection] | None]: """Infer the parser to use for the docstring. @@ -149,14 +147,7 @@ def infer_docstring_style( """ from griffelib._internal.docstrings.parsers import parsers # noqa: PLC0415 - # YORE: Bump 2: Replace block with `per_style_options = per_style_options or {}`. - if options: - if per_style_options: - raise ValueError("Cannot use both `options` and `per_style_options`.") - warn("`**options` is deprecated. Use `per_style_options` instead.", DeprecationWarning, stacklevel=2) - per_style_options = {"google": options, "numpy": options, "sphinx": options} # type: ignore[assignment] - elif not per_style_options: - per_style_options = {} + per_style_options = per_style_options or {} style_order = [Parser(style) if isinstance(style, str) else style for style in style_order or _default_style_order] @@ -203,8 +194,6 @@ def parse_auto( style_order: list[Parser] | list[DocstringStyle] | None = None, default: Parser | DocstringStyle | None = None, per_style_options: PerStyleOptions | None = None, - # YORE: Bump 2: Remove line. - **options: Any, ) -> list[DocstringSection]: """Parse a docstring by automatically detecting the style it uses. @@ -224,14 +213,7 @@ def parse_auto( """ from griffelib._internal.docstrings.parsers import parse # noqa: PLC0415 - # YORE: Bump 2: Replace block with `per_style_options = per_style_options or {}`. - if options: - if per_style_options: - raise ValueError("Cannot use both `options` and `per_style_options`.") - warn("`**options` are deprecated. Use `per_style_options` instead.", DeprecationWarning, stacklevel=2) - per_style_options = {"google": options, "numpy": options, "sphinx": options} # type: ignore[assignment] - elif not per_style_options: - per_style_options = {} + per_style_options = per_style_options or {} style, sections = infer_docstring_style( docstring, diff --git a/packages/griffelib/src/griffelib/_internal/docstrings/google.py b/packages/griffelib/src/griffelib/_internal/docstrings/google.py index 27b585964..77226190b 100644 --- a/packages/griffelib/src/griffelib/_internal/docstrings/google.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/google.py @@ -892,8 +892,6 @@ def parse_google( warn_unknown_params: bool = True, warn_missing_types: bool = True, warnings: bool = True, - # YORE: Bump 2: Remove line. - **options: Any, ) -> list[DocstringSection]: """Parse a Google-style docstring. @@ -932,9 +930,6 @@ def parse_google( in_code_block = False lines = docstring.lines - # YORE: Bump 2: Remove block. - if options: - warn("Passing additional options is deprecated, these options are ignored.", DeprecationWarning, stacklevel=2) options = { "ignore_init_summary": ignore_init_summary, diff --git a/packages/griffelib/src/griffelib/_internal/docstrings/numpy.py b/packages/griffelib/src/griffelib/_internal/docstrings/numpy.py index 6dcf29de5..3abe79299 100644 --- a/packages/griffelib/src/griffelib/_internal/docstrings/numpy.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/numpy.py @@ -916,8 +916,6 @@ def parse_numpy( warn_unknown_params: bool = True, warn_missing_types: bool = True, warnings: bool = True, - # YORE: Bump 2: Remove line. - **options: Any, ) -> list[DocstringSection]: """Parse a Numpydoc-style docstring. @@ -943,9 +941,6 @@ def parse_numpy( in_code_block = False lines = docstring.lines - # YORE: Bump 2: Remove block. - if options: - warn("Passing additional options is deprecated, these options are ignored.", DeprecationWarning, stacklevel=2) options = { "trim_doctest_flags": trim_doctest_flags, diff --git a/packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py b/packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py index 2a24d8f1b..bf014a095 100644 --- a/packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py +++ b/packages/griffelib/src/griffelib/_internal/docstrings/sphinx.py @@ -98,8 +98,6 @@ def parse_sphinx( *, warn_unknown_params: bool = True, warnings: bool = True, - # YORE: Bump 2: Remove line. - **options: Any, ) -> list[DocstringSection]: """Parse a Sphinx-style docstring. @@ -114,9 +112,6 @@ def parse_sphinx( """ parsed_values = _ParsedValues() - # YORE: Bump 2: Remove block. - if options: - warn("Passing additional options is deprecated, these options are ignored.", DeprecationWarning, stacklevel=2) options = { "warn_unknown_params": warn_unknown_params, diff --git a/packages/griffelib/src/griffelib/_internal/encoders.py b/packages/griffelib/src/griffelib/_internal/encoders.py index 5b3ef641c..fca73bd8e 100644 --- a/packages/griffelib/src/griffelib/_internal/encoders.py +++ b/packages/griffelib/src/griffelib/_internal/encoders.py @@ -202,11 +202,7 @@ def _load_module(obj_dict: dict[str, Any]) -> Module: runtime=obj_dict.get("runtime", True), analysis=obj_dict.get("analysis"), ) - # YORE: Bump 2: Replace line with `members = obj_dict.get("members", {}).values()`. - members = obj_dict.get("members", []) - # YORE: Bump 2: Remove block. - if isinstance(members, dict): - members = members.values() + members = obj_dict.get("members", {}).values() for module_member in members: module.set_member(module_member.name, module_member) @@ -234,11 +230,7 @@ def _load_class(obj_dict: dict[str, Any]) -> Class: runtime=obj_dict.get("runtime", True), analysis=obj_dict.get("analysis"), ) - # YORE: Bump 2: Replace line with `members = obj_dict.get("members", {}).values()`. - members = obj_dict.get("members", []) - # YORE: Bump 2: Remove block. - if isinstance(members, dict): - members = members.values() + members = obj_dict.get("members", {}).values() for class_member in members: class_.set_member(class_member.name, class_member) diff --git a/packages/griffelib/src/griffelib/_internal/extensions/base.py b/packages/griffelib/src/griffelib/_internal/extensions/base.py index 50a68c73b..1bc27e699 100644 --- a/packages/griffelib/src/griffelib/_internal/extensions/base.py +++ b/packages/griffelib/src/griffelib/_internal/extensions/base.py @@ -28,37 +28,6 @@ from griffelib._internal.models import Alias, Attribute, Class, Function, Module, Object, TypeAlias -# YORE: Bump 2: Remove block. -class _ExtensionMetaclass(type): - """Metaclass for Griffe extensions.""" - - def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> _ExtensionMetaclass: - if "on_package_loaded" in attrs: - warnings.warn( - "The `on_package_loaded` event is deprecated and renamed to `on_package`.", - DeprecationWarning, - stacklevel=2, - ) - if "on_alias" in attrs: - parameters = inspect.signature(attrs["on_alias"]).parameters - if "node" in parameters or "agent" in parameters: - attrs["__old_on_alias"] = True - warnings.warn( - "The `on_alias` event is now a load event and receives the `alias` and `loader` parameters. " - "It doesn't receive the `node` or `agent` parameters anymore. " - "Please use the new `on_alias` signature, or rename your hook to `on_alias_instance`.", - DeprecationWarning, - stacklevel=1, - ) - if "on_wildcard_expansion" in attrs: - warnings.warn( - "The `on_wildcard_expansion` event is deprecated. " - "Instead, hook onto the `on_alias` event " - "and check for aliases' `wildcard_imported` boolean attribute.", - DeprecationWarning, - stacklevel=2, - ) - return super().__new__(cls, name, bases, attrs) class Extension(metaclass=_ExtensionMetaclass): @@ -469,9 +438,6 @@ def on_package(self, *, pkg: Module, loader: GriffeLoader, **kwargs: Any) -> Non loader: The loader currently in use. **kwargs: For forward-compatibility. """ - # YORE: Bump 2: Remove block. - if hasattr(self, "on_package_loaded"): - self.on_package_loaded(pkg=pkg, loader=loader, **kwargs) LoadableExtensionType = Union[str, dict[str, Any], Extension, type[Extension]] @@ -510,12 +476,7 @@ def call(self, event: str, **kwargs: Any) -> None: **kwargs: Arguments passed to the hook. """ for extension in self._extensions: - # YORE: Bump 2: Replace block with line 5. - if event == "on_alias" and getattr(extension, "__old_on_alias", False): - with suppress(TypeError): - getattr(extension, event)(**kwargs) - else: - getattr(extension, event, self._noop)(**kwargs) + getattr(extension, event, self._noop)(**kwargs) builtin_extensions: set[str] = { diff --git a/packages/griffelib/src/griffelib/_internal/git.py b/packages/griffelib/src/griffelib/_internal/git.py index 7ea952efa..d3ab094db 100644 --- a/packages/griffelib/src/griffelib/_internal/git.py +++ b/packages/griffelib/src/griffelib/_internal/git.py @@ -1,4 +1,4 @@ -# This module contains Git utilities, used by our [`load_git`][griffelib.load_git] function, +# This module contains Git utilities, used by our [`load_git`][griffe.load_git] function, # which in turn is used to load the API for different snapshots of a Git repository # and find breaking changes between them. diff --git a/packages/griffelib/src/griffelib/_internal/loader.py b/packages/griffelib/src/griffelib/_internal/loader.py index c82b502ce..517a4f02b 100644 --- a/packages/griffelib/src/griffelib/_internal/loader.py +++ b/packages/griffelib/src/griffelib/_internal/loader.py @@ -446,8 +446,6 @@ def expand_wildcards( # Everything went right (supposedly), we add the alias as a member of the current object. obj.set_member(new_member.name, alias) - # YORE: Bump 2: Remove line. - self.extensions.call("on_wildcard_expansion", alias=alias, loader=self) def resolve_module_aliases( self, diff --git a/scripts/griffe_exts.py b/scripts/griffe_exts.py deleted file mode 100644 index 81c1e87f9..000000000 --- a/scripts/griffe_exts.py +++ /dev/null @@ -1,24 +0,0 @@ -# YORE: Bump 2: Remove file. - -from typing import Any - -import griffelib - - -class ModuleGetAttrExtension(griffelib.Extension): - def on_package(self, *, pkg: griffelib.Module, **kwargs: Any) -> None: # noqa: ARG002,D102 - if pkg.name == "griffe": - for name in griffelib._deprecated_names: - try: - target = pkg[f"_internal.git._{name}"] - except KeyError: - # Old version where the utility was not yet renamed. - continue - pkg.set_member(name, griffelib.Alias(name, target=f"griffe._internal.git._{name}")) - admonition = griffelib.DocstringSectionAdmonition( - kind="danger", - text="", - title="This function is deprecated and will become unavailable in the next major version.", - ) - target.docstring.parsed.insert(1, admonition) - target.labels.add("deprecated") diff --git a/tests/test_api.py b/tests/test_api.py index afe12e255..d641826e6 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -20,8 +20,6 @@ def _fixture_loader() -> griffelib.GriffeLoader: loader = griffelib.GriffeLoader( extensions=griffe.load_extensions( "griffe_inherited_docstrings", - # YORE: Bump 2: Remove line. - "scripts/griffe_exts.py", "unpack_typeddict", ), ) diff --git a/tests/test_extensions/test_base.py b/tests/test_extensions/test_base.py index f0a086135..3b77c2a74 100644 --- a/tests/test_extensions/test_base.py +++ b/tests/test_extensions/test_base.py @@ -196,82 +196,12 @@ def method(self): ... assert set(events) == set(extension.records) -# YORE: Bump 2: Remove block. -def test_on_alias_renamed_to_on_alias_instance() -> None: - """Hook still runs, a deprecation warning is emitted when the class is declared.""" - with pytest.warns(DeprecationWarning, match="`on_alias` event is now a load event"): - class Ext(Extension): - def __init__(self) -> None: - self.records: list[str] = [] - def on_alias( # type: ignore[override] - self, - *, - node: ast.AST | ObjectNode, # noqa: ARG002 - alias: Alias, # noqa: ARG002 - agent: Visitor | Inspector, # noqa: ARG002 - **kwargs: Any, # noqa: ARG002 - ) -> None: - self.records.append("called as on_alias_instance") - extension = Ext() - with temporary_visited_module("import x", extensions=load_extensions(extension)): - assert extension.records == ["called as on_alias_instance"] -# YORE: Bump 2: Remove block. -def test_new_on_alias_event() -> None: - """No deprecation warning, hook is correctly called.""" - class Ext(Extension): - def __init__(self) -> None: - self.records: list[str] = [] - - def on_alias(self, *, alias: Alias, loader: GriffeLoader, **kwargs: Any) -> None: # noqa: ARG002 - self.records.append("called as on_alias") - - extension = Ext() - with temporary_visited_package("pkg", {"__init__.py": "import x"}, extensions=load_extensions(extension)): - assert extension.records == ["called as on_alias"] - - -# YORE: Bump 2: Remove block. -def test_deprecated_on_package_loaded_event() -> None: - """Hook still runs, a deprecation warning is emitted when the class is declared.""" - with pytest.warns(DeprecationWarning, match="`on_package_loaded` event is deprecated and renamed"): - - class Ext(Extension): - def __init__(self) -> None: - self.records: list[str] = [] - - def on_package_loaded(self, *, pkg: Module, loader: GriffeLoader, **kwargs: Any) -> None: # noqa: ARG002 - self.records.append("called as on_package") - - extension = Ext() - with temporary_visited_package("pkg", {}, extensions=load_extensions(extension)): - assert extension.records == ["called as on_package"] - - -# YORE: Bump 2: Remove block. -def test_deprecated_on_wildcard_expansion_event() -> None: - """Hook still runs, a deprecation warning is emitted when the class is declared.""" - with pytest.warns(DeprecationWarning, match="`on_wildcard_expansion` event is deprecated"): - - class Ext(Extension): - def __init__(self) -> None: - self.records: list[str] = [] - - def on_wildcard_expansion(self, *, alias: Alias, loader: GriffeLoader, **kwargs: Any) -> None: # noqa: ARG002 - self.records.append("called as on_wildcard_expansion") - - extension = Ext() - with temporary_visited_package( - "pkg", - {"__init__.py": "from pkg.module import *", "module.py": "def func(): ..."}, - extensions=load_extensions(extension), - ): - assert extension.records == ["called as on_wildcard_expansion"] class LoadEventsTest(Extension): # noqa: D101