Skip to content

generic functions with @generic #86

@KotlinIsland

Description

@KotlinIsland

pep-695 doesn't address specifying type vars on generic function calls or the reification of generic parameters. What about something like the following:

from basedtyping import generic

@generic
def foo[T](t: T) -> T:
    return t

foo[object](1)

@generic
def bar[T](type_vars, t: T) -> T:
    if issubclass(type_vars.T, int):
        return t + 1
    return t

print(bar[object](1))  # 1
print(bar[int](1))  # 2

and an impl like:

Details

import dataclasses
import inspect
from typing import Callable


@dataclasses.dataclass
class Args:
    _args: object
    _params: object
    def __getattr__(self, attr):
        for i, arg in enumerate(self._params):
            if arg.__name__ == attr:
                return self._args[i]
        super().__getattribute__(attr)

@dataclasses.dataclass
class GenericFunction:
    fn: Callable
    args: tuple = ()

    def __call__(self, *args, **kwargs):
        if tuple(inspect.signature(self.fn).parameters.keys())[0] == "type_vars":
            if not self.args:
                raise TypeError("You have to supply the args...")
            return self.fn(self.args, *args, **kwargs)
        self.fn(*args, **kwargs)

    def __getitem__(self, item):
        if not isinstance(item, tuple):
            item = (item,)
        return GenericFunction(self.fn, Args(item, self.fn.__type_params__))

def generic(fn: Fn) -> GenericFunction:
    return GenericFunction(fn)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions