Kafka4PresidentNow
Kafka4PresidentNow

Reputation: 396

How to annotate optional dict keys with Python 3.9 standard annotations?

I'm trying to understand how to use Python 3.9 type hint to annotate a function that receives a dict with optional or multiple type values. I know that with Typing module, I can use easily Union and Optional. But I'd like to know if it is possible to achieve that using only Python 3.9 annotations. I didn't found anything on this matter on PEP 585.

Reference: How should I use the Optional type hint?

Example:

From Typing import Dict, Optional, Union

def foo(bar: Dict[Union[str, int], Optional[str]]) -> bool: return True

Should I do instead:

from __future__ import annotations

def foo(bar: dict[[str, int], [str, None]) -> bool: return True

Upvotes: 2

Views: 7626

Answers (2)

Samwise
Samwise

Reputation: 71542

No; the enhancements to type annotations in Python 3.9 do not include making Optional or Union builtins. You'll still need to import those from typing.

As of Python 3.10, you can use the | operator to indicate a union type.

If you expect the dictionary to have specific key/value types, a TypedDict that gives different types for different values is generally a better option than using tricky union types to cover all the values in any case.

Upvotes: 6

Fred Truter
Fred Truter

Reputation: 666

In short, it depends on your linter. Visual Studio Code right now has a Python plugin v2020.11.371526539 which supports the following syntax.

from __future__ import annotations

def foo(bar: dict[str | int, str | None]) -> bool | int: 
  return True

IntelliSense displays a helpful preview: enter image description here

And also for the return type: enter image description here

For reference my selected linter is pyre-check version 857747d8246cde76501481378a6b7cf2e7072a2c and python version 3.9.0

Upvotes: 3

Related Questions