29

What is the python way to define a (non-class) type like:

typedef Dict[Union[int, str], Set[str]] RecordType
2
  • In what context - do you want to define a new type that you can then use for type hints? Commented Oct 5, 2021 at 7:10
  • GenericAlias Commented Oct 5, 2021 at 7:14

2 Answers 2

35

This would simply do it?

from typing import Dict, Union, Set

RecordType = Dict[Union[int, str], Set[str]]


def my_func(rec: RecordType):
    pass


my_func({1: {'2'}})
my_func({1: {2}})

This code will generate a warning from your IDE on the second call to my_func, but not on the first. As @sahasrara62 indicated, more here https://docs.python.org/3/library/stdtypes.html#types-genericalias

Since Python 3.9, the preferred syntax would be:

from typing import Union

RecordType = dict[Union[int, str], set[str]]

The built-in types can be used directly for type hints and the added imports are no longer required.

Since Python 3.10, the preferred syntax is

RecordType = dict[int | str, set[str]]

The | operator is a simpler way to create a union of types, and the import of Union is no longer required.

Since Python 3.12, the preferred syntax is

type RecordType = dict[int | str, set[str]]

The type keyword explicitly indicates that this is a type alias.

Sign up to request clarification or add additional context in comments.

1 Comment

I love how elegant and easy to understand Python's syntax is
11

In case users look for a distinct nominal typedef:

from typing import Dict, Union, Set, NewType

RecordType = Dict[Union[int, str], Set[str]]
DistinctRecordType = NewType("DistinctRecordType", Dict[Union[int, str], Set[str]])

def foo(rec: RecordType):
    pass

def bar(rec: DistinctRecordType):
    pass

foo({1: {"2"}})
bar(DistinctRecordType({1: {"2"}}))
bar({1: {"2"}}) # <--- this will cause a type error

This snippet demonstrates that only explicit casting will do.

$ mypy main.py
main.py:14: error: Argument 1 to "bar" has incompatible type "Dict[int, Set[str]]"; expected "DistinctRecordType"
Found 1 error in 1 file (checked 1 source file)

Comments

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.