Reputation: 396
I would like to create custom Python type hint that would effectively be
MyType = Dict[str, <some_type>]
Then I would like to be able to spesify MyType
like MyType[<some_type>]
, for example
MyType[List[str]]
which would mean Dict[str, List[str]]
.
I haven't been able to figure out how to do this.
I've tried MyType = Dict[str, Any]
but I don't know how to make Any
be a variable. Any suggestions?
Upvotes: 2
Views: 1435
Reputation: 1584
Does Generics answer your question?
from typing import TypeVar, Dict, List
X = TypeVar('X')
MyType = Dict[str, X]
def test_f(d: MyType[List[str]]) -> bool:
pass
Upvotes: 3
Reputation: 934
If you're using Python 3.9 or newer, you can use standard collections directly:
StrList = list[str]
MyType = dict[str, StrList]
If you're using Python 3.7 or 3.8, you can still use the new notation via
from __future__ import annotations
Note: __future__
import statements must be located at the very top of a module
Upvotes: -1