Mark Amery
Mark Amery

Reputation: 154745

Can generic type hints like Dict and List be used bare, without square brackets?

The docs on Dict show it being used as a generic type, like this:

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
    return word_list[word]

It would also, of course, be correct to type-hint word_list above as dict:

def get_position_in_index(word_list: dict, word: str) -> int:
    return word_list[word]

But is it correct to use Dict as a type-hint on its own to indicate a dict with keys and values of any type, like this?

def get_position_in_index(word_list: Dict, word: str) -> int:
    return word_list[word]

(And likewise, can other generic types like List and Sequence be used bare in this way?)

Upvotes: 3

Views: 4345

Answers (1)

Michael0x2a
Michael0x2a

Reputation: 64108

Yes, Dict is considered to be an alias for Dict[Any, Any]. (And dict is also an alias for Dict[Any, Any]).

This is the case for any generic type, whether it's a builtin one or a custom-made one: if you omit the type parameters, they always default to Any. This is specified in the Generics section of PEP 484 (emphasis added):

Additionally, Any is a valid value for every type variable. Consider the following:

def count_truthy(elements: List[Any]) -> int:
    return sum(1 for elem in elements if element)

This is equivalent to omitting the generic notation and just saying elements: List.

That said, I think the general recommendation is that you should fully write out Dict[Any, Any] instead of using just Dict -- explicit is better then implicit, and so forth.

The only downside is that your function type signatures are now longer. But we can work around that by using type aliases:

from typing import Dict, Any

AnyDict = Dict[Any, Any]
WordDict = Dict[str, int]

# Equivalent to your first code sample
def get_position_in_index_1(word_list: WordDict, word: str) -> int:
    return word_list[word]

# Equivalent to your second and third code samples
def get_position_in_index_2(word_list: AnyDict, word: str) -> int:
    return word_list[word]

Upvotes: 5

Related Questions