Input type, custom collection type

A typical module provides some handy functions to provide better readability and more confidence in the correctness of the entered code.

One of the best features is that you can write something like below to describe an input dictionary with specified element types.

def myFun(inputDict:Dict[str, int]): pass

      

Now I'm wondering if this could be "extended" for custom types? Can custom types (which act like containers) provide indexes in a formal way to tell a potential type validator that the content should be of a specific type?

For example, a class collections.Counter

? - Above restrictions won't work when I really want a counter, since dictionaries don't provide an addition operator where counters do.

I could do something like:

def myFun(inputDict:collections.Counter): pass

      

But then I lose information about what the counter stores. - Is using the TypeVar

correct approach here?

CounterTy = typing.TypeVar("CounterTy", collections.Counter)
def myFun(inputDict:CounterTy[str]): pass

      

I don't understand if it should TypeVar

work this way or not. EDIT: just to be clear, the code above doesn't work and there are errors in the line TypeVar

.

+3


source to share


1 answer


If you write your own container type and want to parameterize it in the same way typing.Dict

with other types, you should use typing.Generic

as one of your bases (with TypeVar

as a parameter):



from typing import TypeVar, Generic, Iterable

T = TypeVar('T')

class MyContainer(Generic[T]):
    def __init__(self, iterable:Iterable[T]):
        ...

    def foo(self) -> T:
        ...

def some_function(arg: MyContainer[str]) -> str:
    return arg.foo()

      

+1


source







All Articles