Coverage for packages / griffelib / src / griffe / __init__.py: 84.62%
50 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-11 11:48 +0100
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-11 11:48 +0100
1# This top-level module imports all public names from the package,
2# and exposes them as public objects. We have tests to make sure
3# no object is forgotten in this list.
5"""Griffe library package.
7Signatures for entire Python programs.
8Extract the structure, the frame, the skeleton of your project,
9to generate API documentation or find breaking changes in your API.
11The entirety of the library API is exposed here, in the top-level `griffe` module.
13All messages written to standard output or error are logged using the `logging` module.
14Our logger's name is set to `"griffe"` and is public (you can rely on it).
15You can obtain the logger from the standard `logging` module: `logging.getLogger("griffe")`.
16Actual logging messages are not part of the public API (they might change without notice).
18Raised exceptions throughout the package are part of the public API (you can rely on them).
19Their actual messages are not part of the public API (they might change without notice).
21The following paragraphs will help you discover the package's content.
23## Loaders
25To load API data, Griffe provides several high-level functions.
27- [`griffe.load`][]: Load and return a Griffe object.
28- [`griffe.load_git`][]: Load and return a module from a specific Git reference.
29- [`griffe.load_pypi`][]: Load and return a module from a specific package version downloaded using pip.
31## Models
33The data loaded by Griffe is represented by several classes.
35- [`griffe.Module`][]: The class representing a Python module.
36- [`griffe.Class`][]: The class representing a Python class.
37- [`griffe.Function`][]: The class representing a Python function or method.
38- [`griffe.Attribute`][]: The class representing a Python attribute.
39- [`griffe.Alias`][]: This class represents an alias, or indirection, to an object declared in another module.
41Additional classes are available to represent other concepts.
43- [`griffe.Decorator`][]: This class represents a decorator.
44- [`griffe.Parameters`][]: This class is a container for parameters.
45- [`griffe.Parameter`][]: This class represent a function parameter.
47## Agents
49Griffe is able to analyze code both statically and dynamically, using the following "agents".
50However most of the time you will only need to use the loaders above.
52- [`griffe.visit`][]: Parse and visit a module file.
53- [`griffe.inspect`][]: Inspect a module.
55## Serializers
57Griffe can serizalize data to dictionary and JSON.
59- [`griffe.Object.as_json`][griffe.Object.as_json]
60- [`griffe.Object.from_json`][griffe.Object.from_json]
61- [`griffe.JSONEncoder`][]: JSON encoder for Griffe objects.
62- [`griffe.json_decoder`][]: JSON decoder for Griffe objects.
64## API checks
66Griffe can compare two versions of the same package to find breaking changes.
68- [`griffe.find_breaking_changes`][]: Find breaking changes between two versions of the same API.
69- [`griffe.Breakage`][]: Breakage classes can explain what broke from a version to another.
71## Extensions
73Griffe supports extensions. You can create your own extension by subclassing the `griffe.Extension` class.
75- [`griffe.load_extensions`][]: Load configured extensions.
76- [`griffe.Extension`][]: Base class for Griffe extensions.
78## Docstrings
80Griffe can parse docstrings into structured data.
82Main class:
84- [`griffe.Docstring`][]: This class represents docstrings.
86Docstring section and element classes all start with `Docstring`.
88Docstring parsers:
90- [`griffe.parse`][]: Parse the docstring.
91- [`griffe.parse_auto`][]: Parse a docstring by automatically detecting the style it uses.
92- [`griffe.parse_google`][]: Parse a Google-style docstring.
93- [`griffe.parse_numpy`][]: Parse a Numpydoc-style docstring.
94- [`griffe.parse_sphinx`][]: Parse a Sphinx-style docstring.
96## Exceptions
98Griffe uses several exceptions to signal errors.
100- [`griffe.GriffeError`][]: The base exception for all Griffe errors.
101- [`griffe.LoadingError`][]: Exception for loading errors.
102- [`griffe.NameResolutionError`][]: Exception for names that cannot be resolved in a object scope.
103- [`griffe.UnhandledEditableModuleError`][]: Exception for unhandled editables modules, when searching modules.
104- [`griffe.UnimportableModuleError`][]: Exception for modules that cannot be imported.
105- [`griffe.AliasResolutionError`][]: Exception for aliases that cannot be resolved.
106- [`griffe.CyclicAliasError`][]: Exception raised when a cycle is detected in aliases.
107- [`griffe.LastNodeError`][]: Exception raised when trying to access a next or previous node.
108- [`griffe.RootNodeError`][]: Exception raised when trying to use siblings properties on a root node.
109- [`griffe.BuiltinModuleError`][]: Exception raised when trying to access the filepath of a builtin module.
110- [`griffe.ExtensionError`][]: Base class for errors raised by extensions.
111- [`griffe.ExtensionNotLoadedError`][]: Exception raised when an extension could not be loaded.
112- [`griffe.GitError`][]: Exception raised for errors related to Git.
114# Expressions
116Griffe stores snippets of code (attribute values, decorators, base class, type annotations) as expressions.
117Expressions are basically abstract syntax trees (AST) with a few differences compared to the nodes returned by [`ast`][].
118Griffe provides a few helpers to extract expressions from regular AST nodes.
120- [`griffe.get_annotation`][]: Get a type annotation as expression.
121- [`griffe.get_base_class`][]: Get a base class as expression.
122- [`griffe.get_class_keyword`][]: Get a class keyword as expression.
123- [`griffe.get_condition`][]: Get a condition as expression.
124- [`griffe.get_expression`][]: Get an expression from an AST node.
125- [`griffe.safe_get_annotation`][]: Get a type annotation as expression, safely (returns `None` on error).
126- [`griffe.safe_get_base_class`][]: Get a base class as expression, safely (returns `None` on error).
127- [`griffe.safe_get_class_keyword`][]: Get a class keyword as expression, safely (returns `None` on error).
128- [`griffe.safe_get_condition`][]: Get a condition as expression, safely (returns `None` on error).
129- [`griffe.safe_get_expression`][]: Get an expression from an AST node, safely (returns `None` on error).
131The base class for expressions.
133- [`griffe.Expr`][]
135Expression classes all start with `Expr`.
137# Loggers
139If you want to log messages from extensions, get a logger with `get_logger`.
140The `logger` attribute is used by Griffe itself. You can use it to temporarily disable Griffe logging.
142- [`griffe.logger`][]: Our global logger, used throughout the library.
143- [`griffe.get_logger`][]: Create and return a new logger instance.
145# Helpers
147To test your Griffe extensions, or to load API data from code in memory, Griffe provides the following helpers.
149- [`griffe.temporary_pyfile`][]: Create a Python file containing the given code in a temporary directory.
150- [`griffe.temporary_pypackage`][]: Create a package containing the given modules in a temporary directory.
151- [`griffe.temporary_visited_module`][]: Create and visit a temporary module with the given code.
152- [`griffe.temporary_visited_package`][]: Create and visit a temporary package.
153- [`griffe.temporary_inspected_module`][]: Create and inspect a temporary module with the given code.
154- [`griffe.temporary_inspected_package`][]: Create and inspect a temporary package.
155"""
157from __future__ import annotations
159from griffe._internal.agents.inspector import Inspector, inspect
160from griffe._internal.agents.nodes.assignments import get_instance_names, get_name, get_names
161from griffe._internal.agents.nodes.ast import (
162 ast_children,
163 ast_first_child,
164 ast_kind,
165 ast_last_child,
166 ast_next,
167 ast_next_siblings,
168 ast_previous,
169 ast_previous_siblings,
170 ast_siblings,
171)
172from griffe._internal.agents.nodes.docstrings import get_docstring
173from griffe._internal.agents.nodes.exports import get__all__, safe_get__all__
174from griffe._internal.agents.nodes.imports import relative_to_absolute
175from griffe._internal.agents.nodes.parameters import ParametersType, get_parameters
176from griffe._internal.agents.nodes.runtime import ObjectNode
177from griffe._internal.agents.nodes.values import get_value, safe_get_value
178from griffe._internal.agents.visitor import Visitor, builtin_decorators, stdlib_decorators, typing_overload, visit
179from griffe._internal.c3linear import c3linear_merge
180from griffe._internal.collections import LinesCollection, ModulesCollection
181from griffe._internal.diff import (
182 AttributeChangedTypeBreakage,
183 AttributeChangedValueBreakage,
184 Breakage,
185 ClassRemovedBaseBreakage,
186 ObjectChangedKindBreakage,
187 ObjectRemovedBreakage,
188 ParameterAddedRequiredBreakage,
189 ParameterChangedDefaultBreakage,
190 ParameterChangedKindBreakage,
191 ParameterChangedRequiredBreakage,
192 ParameterMovedBreakage,
193 ParameterRemovedBreakage,
194 ReturnChangedTypeBreakage,
195 find_breaking_changes,
196)
197from griffe._internal.docstrings.auto import (
198 AutoOptions,
199 DocstringDetectionMethod,
200 PerStyleOptions,
201 infer_docstring_style,
202 parse_auto,
203)
204from griffe._internal.docstrings.google import GoogleOptions, parse_google
205from griffe._internal.docstrings.models import (
206 DocstringAdmonition,
207 DocstringAttribute,
208 DocstringClass,
209 DocstringDeprecated,
210 DocstringElement,
211 DocstringFunction,
212 DocstringModule,
213 DocstringNamedElement,
214 DocstringParameter,
215 DocstringRaise,
216 DocstringReceive,
217 DocstringReturn,
218 DocstringSection,
219 DocstringSectionAdmonition,
220 DocstringSectionAttributes,
221 DocstringSectionClasses,
222 DocstringSectionDeprecated,
223 DocstringSectionExamples,
224 DocstringSectionFunctions,
225 DocstringSectionModules,
226 DocstringSectionOtherParameters,
227 DocstringSectionParameters,
228 DocstringSectionRaises,
229 DocstringSectionReceives,
230 DocstringSectionReturns,
231 DocstringSectionText,
232 DocstringSectionTypeAliases,
233 DocstringSectionTypeParameters,
234 DocstringSectionWarns,
235 DocstringSectionYields,
236 DocstringTypeAlias,
237 DocstringTypeParameter,
238 DocstringWarn,
239 DocstringYield,
240)
241from griffe._internal.docstrings.numpy import NumpyOptions, parse_numpy
242from griffe._internal.docstrings.parsers import (
243 DocstringOptions,
244 DocstringStyle,
245 parse,
246 parsers,
247)
248from griffe._internal.docstrings.sphinx import SphinxOptions, parse_sphinx
249from griffe._internal.docstrings.utils import docstring_warning, parse_docstring_annotation
250from griffe._internal.encoders import JSONEncoder, json_decoder
251from griffe._internal.enumerations import (
252 BreakageKind,
253 DocstringSectionKind,
254 ExplanationStyle,
255 Kind,
256 LogLevel,
257 ObjectKind,
258 ParameterKind,
259 Parser,
260 TypeParameterKind,
261)
262from griffe._internal.exceptions import (
263 AliasResolutionError,
264 BuiltinModuleError,
265 CyclicAliasError,
266 ExtensionError,
267 ExtensionNotLoadedError,
268 GitError,
269 GriffeError,
270 LastNodeError,
271 LoadingError,
272 NameResolutionError,
273 RootNodeError,
274 UnhandledEditableModuleError,
275 UnimportableModuleError,
276)
277from griffe._internal.expressions import (
278 Expr,
279 ExprAttribute,
280 ExprBinOp,
281 ExprBoolOp,
282 ExprCall,
283 ExprCompare,
284 ExprComprehension,
285 ExprConstant,
286 ExprDict,
287 ExprDictComp,
288 ExprExtSlice,
289 ExprFormatted,
290 ExprGeneratorExp,
291 ExprIfExp,
292 ExprInterpolation,
293 ExprJoinedStr,
294 ExprKeyword,
295 ExprLambda,
296 ExprList,
297 ExprListComp,
298 ExprName,
299 ExprNamedExpr,
300 ExprParameter,
301 ExprSet,
302 ExprSetComp,
303 ExprSlice,
304 ExprSubscript,
305 ExprTemplateStr,
306 ExprTuple,
307 ExprUnaryOp,
308 ExprVarKeyword,
309 ExprVarPositional,
310 ExprYield,
311 ExprYieldFrom,
312 get_annotation,
313 get_base_class,
314 get_class_keyword,
315 get_condition,
316 get_expression,
317 safe_get_annotation,
318 safe_get_base_class,
319 safe_get_class_keyword,
320 safe_get_condition,
321 safe_get_expression,
322)
323from griffe._internal.extensions.base import (
324 Extension,
325 Extensions,
326 LoadableExtensionType,
327 builtin_extensions,
328 load_extensions,
329)
330from griffe._internal.extensions.dataclasses import DataclassesExtension
331from griffe._internal.extensions.unpack_typeddict import UnpackTypedDictExtension
332from griffe._internal.finder import ModuleFinder, NamePartsAndPathType, NamePartsType, NamespacePackage, Package
333from griffe._internal.git import GitInfo, KnownGitService
334from griffe._internal.importer import dynamic_import, sys_path
335from griffe._internal.loader import GriffeLoader, load, load_git, load_pypi
336from griffe._internal.logger import Logger, get_logger, logger, patch_loggers
337from griffe._internal.merger import merge_stubs
338from griffe._internal.mixins import (
339 DelMembersMixin,
340 GetMembersMixin,
341 ObjectAliasMixin,
342 SerializationMixin,
343 SetMembersMixin,
344)
345from griffe._internal.models import (
346 Alias,
347 Attribute,
348 Class,
349 Decorator,
350 Docstring,
351 Function,
352 Module,
353 Object,
354 Parameter,
355 Parameters,
356 TypeAlias,
357 TypeParameter,
358 TypeParameters,
359)
360from griffe._internal.stats import Stats
361from griffe._internal.tests import (
362 TmpPackage,
363 htree,
364 module_vtree,
365 temporary_inspected_module,
366 temporary_inspected_package,
367 temporary_pyfile,
368 temporary_pypackage,
369 temporary_visited_module,
370 temporary_visited_package,
371 vtree,
372)
374# Regenerate this list with the following Python snippet:
375# import griffe
376# names = sorted(n for n in dir(griffe) if not n.startswith("_") and n not in ("annotations",))
377# print('__all__ = [\n "' + '",\n "'.join(names) + '",\n]')
378__all__ = [
379 "Alias",
380 "AliasResolutionError",
381 "Attribute",
382 "AttributeChangedTypeBreakage",
383 "AttributeChangedValueBreakage",
384 "AutoOptions",
385 "Breakage",
386 "BreakageKind",
387 "BuiltinModuleError",
388 "Class",
389 "ClassRemovedBaseBreakage",
390 "CyclicAliasError",
391 "DataclassesExtension",
392 "Decorator",
393 "DelMembersMixin",
394 "Docstring",
395 "DocstringAdmonition",
396 "DocstringAttribute",
397 "DocstringClass",
398 "DocstringDeprecated",
399 "DocstringDetectionMethod",
400 "DocstringElement",
401 "DocstringFunction",
402 "DocstringModule",
403 "DocstringNamedElement",
404 "DocstringOptions",
405 "DocstringParameter",
406 "DocstringRaise",
407 "DocstringReceive",
408 "DocstringReturn",
409 "DocstringSection",
410 "DocstringSectionAdmonition",
411 "DocstringSectionAttributes",
412 "DocstringSectionClasses",
413 "DocstringSectionDeprecated",
414 "DocstringSectionExamples",
415 "DocstringSectionFunctions",
416 "DocstringSectionKind",
417 "DocstringSectionModules",
418 "DocstringSectionOtherParameters",
419 "DocstringSectionParameters",
420 "DocstringSectionRaises",
421 "DocstringSectionReceives",
422 "DocstringSectionReturns",
423 "DocstringSectionText",
424 "DocstringSectionTypeAliases",
425 "DocstringSectionTypeParameters",
426 "DocstringSectionWarns",
427 "DocstringSectionYields",
428 "DocstringStyle",
429 "DocstringTypeAlias",
430 "DocstringTypeParameter",
431 "DocstringWarn",
432 "DocstringYield",
433 "ExplanationStyle",
434 "Expr",
435 "ExprAttribute",
436 "ExprBinOp",
437 "ExprBoolOp",
438 "ExprCall",
439 "ExprCompare",
440 "ExprComprehension",
441 "ExprConstant",
442 "ExprDict",
443 "ExprDictComp",
444 "ExprExtSlice",
445 "ExprFormatted",
446 "ExprGeneratorExp",
447 "ExprIfExp",
448 "ExprInterpolation",
449 "ExprJoinedStr",
450 "ExprKeyword",
451 "ExprLambda",
452 "ExprList",
453 "ExprListComp",
454 "ExprName",
455 "ExprNamedExpr",
456 "ExprParameter",
457 "ExprSet",
458 "ExprSetComp",
459 "ExprSlice",
460 "ExprSubscript",
461 "ExprTemplateStr",
462 "ExprTuple",
463 "ExprUnaryOp",
464 "ExprVarKeyword",
465 "ExprVarPositional",
466 "ExprYield",
467 "ExprYieldFrom",
468 "Extension",
469 "ExtensionError",
470 "ExtensionNotLoadedError",
471 "Extensions",
472 "Function",
473 "GetMembersMixin",
474 "GitError",
475 "GitInfo",
476 "GoogleOptions",
477 "GriffeError",
478 "GriffeLoader",
479 "Inspector",
480 "JSONEncoder",
481 "Kind",
482 "KnownGitService",
483 "LastNodeError",
484 "LinesCollection",
485 "LoadableExtensionType",
486 "LoadingError",
487 "LogLevel",
488 "Logger",
489 "Module",
490 "ModuleFinder",
491 "ModulesCollection",
492 "NamePartsAndPathType",
493 "NamePartsType",
494 "NameResolutionError",
495 "NamespacePackage",
496 "NumpyOptions",
497 "Object",
498 "ObjectAliasMixin",
499 "ObjectChangedKindBreakage",
500 "ObjectKind",
501 "ObjectNode",
502 "ObjectRemovedBreakage",
503 "Package",
504 "Parameter",
505 "ParameterAddedRequiredBreakage",
506 "ParameterChangedDefaultBreakage",
507 "ParameterChangedKindBreakage",
508 "ParameterChangedRequiredBreakage",
509 "ParameterKind",
510 "ParameterMovedBreakage",
511 "ParameterRemovedBreakage",
512 "Parameters",
513 "ParametersType",
514 "Parser",
515 "PerStyleOptions",
516 "ReturnChangedTypeBreakage",
517 "RootNodeError",
518 "SerializationMixin",
519 "SetMembersMixin",
520 "SphinxOptions",
521 "Stats",
522 "TmpPackage",
523 "TypeAlias",
524 "TypeParameter",
525 "TypeParameterKind",
526 "TypeParameters",
527 "UnhandledEditableModuleError",
528 "UnimportableModuleError",
529 "UnpackTypedDictExtension",
530 "Visitor",
531 "ast_children",
532 "ast_first_child",
533 "ast_kind",
534 "ast_last_child",
535 "ast_next",
536 "ast_next_siblings",
537 "ast_previous",
538 "ast_previous_siblings",
539 "ast_siblings",
540 "builtin_decorators",
541 "builtin_extensions",
542 "c3linear_merge",
543 "docstring_warning",
544 "dynamic_import",
545 "find_breaking_changes",
546 "get__all__",
547 "get_annotation",
548 "get_base_class",
549 "get_class_keyword",
550 "get_condition",
551 "get_docstring",
552 "get_expression",
553 "get_instance_names",
554 "get_logger",
555 "get_name",
556 "get_names",
557 "get_parameters",
558 "get_value",
559 "htree",
560 "infer_docstring_style",
561 "inspect",
562 "json_decoder",
563 "load",
564 "load_extensions",
565 "load_git",
566 "load_pypi",
567 "logger",
568 "merge_stubs",
569 "module_vtree",
570 "parse",
571 "parse_auto",
572 "parse_docstring_annotation",
573 "parse_google",
574 "parse_numpy",
575 "parse_sphinx",
576 "parsers",
577 "patch_loggers",
578 "relative_to_absolute",
579 "safe_get__all__",
580 "safe_get_annotation",
581 "safe_get_base_class",
582 "safe_get_class_keyword",
583 "safe_get_condition",
584 "safe_get_expression",
585 "safe_get_value",
586 "stdlib_decorators",
587 "sys_path",
588 "temporary_inspected_module",
589 "temporary_inspected_package",
590 "temporary_pyfile",
591 "temporary_pypackage",
592 "temporary_visited_module",
593 "temporary_visited_package",
594 "typing_overload",
595 "visit",
596 "vtree",
597]
599# Re-export griffecli for backward compatibility.
600try:
601 from griffecli import * # noqa: F403
602 from griffecli import __all__ as __cli_all__
603except ImportError:
604 # Keep this in sync with the exported members of griffecli.
605 _MISSING_FROM_GRIFFECLI = {
606 "DEFAULT_LOG_LEVEL",
607 "check",
608 "dump",
609 "get_parser",
610 "main",
611 }
613 def __getattr__(attr: str) -> object:
614 if attr in _MISSING_FROM_GRIFFECLI:
615 raise ImportError(f"Please install `griffecli` to use {'griffe.' + attr!r}")
616 raise AttributeError(attr)
617else:
618 __all__ += __cli_all__ # noqa: PLE0605
619 # Ignore any re-exported API in internal API tests.
620 _REEXPORTED_EXTERNAL_API = set(__cli_all__)