dry-python/classes

Should we be able to annotate `instance` as `delegate` type?

sobolevn opened this issue · 0 comments

I think that we should add a possibility for users to write both:

@some.instance(List[int], delegate=ListOfInt)
def _some_list_int(instance: List[int]) -> int:
    ...

And

@some.instance(List[int], delegate=ListOfInt)
def _some_list_int(instance: ListOfInt) -> int:
    ...

It might be useful in different situations. For example, we can have this function defined:

def sum_list_of_ints(instance: ListOfInt) -> int:
    return sum(instance)

To call it, we need ListOfInt instance, not just List[int]. It might be useful in domain-specific code that uses type-level programming.

But, we need to guarantee some things here:

  1. We need to check that delegate is a strict subtype of instance type
  2. We need to check that delegate respects original type restriction

Rejected idea: type narrowing.

@some.instance(List[int], delegate=ListOfInt)
def _some_list_int(instance: List[int]) -> int:
    assert isinstance(instance, ListOfInt)

It will simply call the same isinstance twice. We don't need this extra step.