Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

generic functions with @generic #86

Open
KotlinIsland opened this issue May 3, 2023 · 0 comments · May be fixed by #98
Open

generic functions with @generic #86

KotlinIsland opened this issue May 3, 2023 · 0 comments · May be fixed by #98
Labels

Comments

@KotlinIsland
Copy link
Owner

KotlinIsland commented May 3, 2023

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)

@KotlinIsland KotlinIsland changed the title GenericFunctions generic functions with @generic May 24, 2023
@KotlinIsland KotlinIsland transferred this issue from KotlinIsland/basedmypy Dec 9, 2023
@KotlinIsland KotlinIsland linked a pull request Dec 21, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant