Can I use square brackets in python to type hint enumerable?

Viewed 46

Can we type hint an enumerable using just square brackets like the following:

def test_dict_to_str(test_dict_lst: [dict]) -> [str]:

The intellisense seems to be ok with this but not sure if this is expected. Can't find any mention of it in pep-8 docs. All I see is usage of list with square brackets

def test_dict_to_str(test_dict_lst: list[dict]) -> list[str]:
1 Answers

I believe you can put any valid identifier there, and your code will run, but it doesn't always mean anything useful, and type checkers will only understand it if it's a valid type. I'm not sure why it's a feature. For example

>>> def foo(x : 1) -> 2:
...     print(x)
... 
>>> foo("hmmm...")
hmmm...

while mypy gives

main.py:1: error: Invalid type: try using Literal[1] instead?
main.py:1: error: Invalid type: try using Literal[2] instead?
Found 2 errors in 1 file (checked 1 source file)

Intellisense is presumably not trying to use it as a type hint.

Related