Skip to content

Instantly share code, notes, and snippets.

@gwerbin
Created November 7, 2022 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwerbin/6567ff7a9165713a0e98401b496f852b to your computer and use it in GitHub Desktop.
Save gwerbin/6567ff7a9165713a0e98401b496f852b to your computer and use it in GitHub Desktop.
Helper to "export" names in a module
from collections import UserString
from collections.abc import Callable, Mapping
from typing import Any, MutableSequence, ParamSpec, Protocol, TypeVar, overload
from typing_extensions import Self, Unpack
class _HasName(Protocol):
__name__: str
_T = TypeVar("_T")
_Named = TypeVar("_Named", bound=_HasName)
class Exporter:
r"""A callable that "exports" objects by appending them to a given ``__all__`` list.
Example:
.. code-block:: python
__all__ = []
_export = Exporter(__all__)
@_export("z")
z = 99
def foo():
return 1
def _special():
return z
@_export
def bar():
return _special() + 1
@_export
class Thing:
x: float
def __init__(self):
self.x = z
"""
_namelist: MutableSequence[str]
def __init__(self, namelist):
self._namelist = namelist
@overload
def __call__(self, obj: str) -> str: ...
@overload
def __call__(self, obj: _Named) -> _Named: ...
def __call__(self, obj: _Named | str) -> _Named | str:
if isinstance(obj, str):
name = obj
else:
name = obj.__name__
self._namelist.append(name)
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment