Skip to content

Instantly share code, notes, and snippets.

@qexat
Last active May 7, 2023 22:34
Show Gist options
  • Save qexat/df01370ee4b1f732bedda84abacdf765 to your computer and use it in GitHub Desktop.
Save qexat/df01370ee4b1f732bedda84abacdf765 to your computer and use it in GitHub Desktop.
One for all - one call, every method
from __future__ import annotations
from collections.abc import Callable, Iterable
import sys
from typing import (
Any,
Generic,
Literal,
LiteralString,
SupportsIndex,
TypeVar,
overload,
)
__all__ = ["array"]
T = TypeVar("T")
def get_type_methods(type: type) -> list[str]:
return [
method
for method in dir(type)
if not method.startswith("_") and not method.endswith("_")
]
class _array_t(Generic[T]):
@overload
def __init__(self) -> None:
pass
@overload
def __init__(self, iterable: Iterable[T]) -> None:
pass
def __init__(self, iterable: Iterable[T] | None = None) -> None:
self.__internal = list(iterable) if iterable else []
def __repr__(self) -> str:
return repr(self.__internal)
@overload
def __call__(self, method: Literal["copy"]) -> _array_t[T]:
pass
@overload
def __call__(self, method: Literal["append"], object: T) -> None:
pass
@overload
def __call__(self, method: Literal["extend"], iterable: Iterable[T]) -> None:
pass
@overload
def __call__(self, method: Literal["pop"], index: SupportsIndex = -1) -> T:
pass
@overload
def __call__(
self,
method: Literal["index"],
value: T,
start: SupportsIndex = 0,
stop: SupportsIndex = sys.maxsize,
) -> int:
pass
@overload
def __call__(self, method: Literal["count"], value: T) -> int:
pass
@overload
def __call__(
self,
method: Literal["insert"],
index: SupportsIndex,
object: T,
) -> None:
pass
@overload
def __call__(self, method: Literal["remove"], value: T) -> None:
pass
@overload
def __call__(
self,
method: Literal["sort"],
*,
key: None = None,
reverse: bool = False,
) -> None:
pass
@overload
def __call__(
self,
method: Literal["sort"],
*,
key: Callable[[T], Any],
reverse: bool = False,
) -> None:
pass
def __call__(self, method: LiteralString, *args: Any, **kwargs: Any) -> Any:
_methods = get_type_methods(list)
if method not in _methods:
raise AttributeError(f"'array' object has no attribute {method!r}")
return self.__internal.__getattribute__(method)(*args, **kwargs)
def array(subtype: type[T], /) -> type[_array_t[T]]:
return _array_t[subtype]
from one4all import array
def main() -> int:
x = array(int)()
x("append", 3)
x("extend", [1, 2, 5])
print(x)
x("sort")
print(x)
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment