Skip to content

Commit

Permalink
feat: Add an is_public helper method to guess if an object is public
Browse files Browse the repository at this point in the history
A `public` attribute is also added to Object and Alias,
allowing extension writers to force an object to be public.
  • Loading branch information
pawamoy committed Aug 23, 2023
1 parent d400cb1 commit b823639
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/griffe/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ def __init__(
self.aliases: dict[str, Alias] = {}
self.runtime: bool = runtime
self.extra: dict[str, dict[str, Any]] = defaultdict(dict)
self.public: bool | None = None
self._lines_collection: LinesCollection | None = lines_collection
self._modules_collection: ModulesCollection | None = modules_collection

Expand Down Expand Up @@ -761,6 +762,7 @@ def __init__(
self.alias_endlineno: int | None = endlineno
self.runtime: bool = runtime
self.inherited: bool = inherited
self.public: bool | None = None
self._parent: Module | Class | Alias | None = parent
self._passed_through: bool = False
if isinstance(target, str):
Expand Down
33 changes: 33 additions & 0 deletions src/griffe/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,39 @@ def is_implicitely_exported(self) -> bool:
"""
return self.parent.exports is None # type: ignore[attr-defined]

def is_public(
self,
*,
strict: bool = False,
check_name: bool = True,
) -> bool:
"""Whether this object is considered public.
In modules, developers can mark objects as public thanks to the `__all__` variable.
In classes however, there is no convention or standard to do so.
Therefore, to decide whether an object is public, we follow this algorithm:
- If the object's `public` attribute is set (boolean), return its value.
- In strict mode, the object is public only if it is explicitely exported (listed in `__all__`).
Strict mode should only be used for module members.
- Otherwise, if name checks are enabled, the object is private if its name starts with an underscore.
- Otherwise, if the object is an alias, and is neither inherited from a base class,
nor a member of a parent alias, it is not public.
- Otherwise, the object is public.
"""
if self.public is not None: # type: ignore[attr-defined]
return self.public # type: ignore[attr-defined]
if self.is_explicitely_exported:
return True
if strict:
return False
if check_name and self.name.startswith("_"): # type: ignore[attr-defined]
return False
if self.is_alias and not (self.inherited or self.parent.is_alias): # type: ignore[attr-defined]
return False
return True


class SerializationMixin:
"""A mixin that adds de/serialization conveniences."""
Expand Down

0 comments on commit b823639

Please sign in to comment.