[FIXED] How to create customizable Python type

Issue

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?


Solution

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


Answered By - Nikolay Zakirov
Answer Checked By - David Goodson (Python.Easybugfix Volunteer)

Related Posts

Post a Comment