2

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

While the mention of standard generic aliases is correct and useful, the code you give doesn't really answer the question. OP actually wanted a generic type that could be specified with one type argument. These are just two type aliases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.