PR: https://github.com/apache/qpid-proton/pull/325

I've focused on simple and mostly obvious declarations there. I want to get
them merged first, and then tackle the ones where e.g. current
documentation does not match the actual types. While working on the PR, I
encountered some less obvious features of Python typing, which I'd like to
briefly mention in the remainder of the email. Chances are that if you are
new to Python typing, you haven't encountered them yet.

# if TYPE_CHECKING

Importing a file just to get type definition sometimes leads to circular
imports. Conditional import like this breaks the cycle for regular
execution; when type-checking, the checkers can deal with the import
cycles, since they are not actually executing the checked code.

# from __future__ import annotations

This is an useful Python language extension, that can be opted into
starting with Python 3.7. When enabled, it stops Python from trying to
evaluate the inline type annotations as it is loading each file. This
allows dropping the single quotes for types that are only defined later in
the file, or are conditionally imported.

# @overload

This allows multiple type signatures for a method. For example, _check_type
does casting in the following way: If an argument of type symbol or str is
given, the function will cast it to a symbol. If allow_ulong is True, then
also ulong return value is possible. If raise_on_error is False, then any
type is accepted and returned. That leads me to a crazy type definition
along the following lines. This is not something that I added to a PR just
yet; I am now focusing on short, sweet and useful types, for now.

_T = TypeVar('_T')

@overload
def _check_type(s: Union[symbol, str], allow_ulong: bool = ...,
raise_on_error: bool = ...) -> symbol:
    ...


@overload
def _check_type(s: Any, allow_ulong: Literal[False] = ..., raise_on_error:
Literal[True] = ...) -> Union[symbol]:
    ...


@overload
def _check_type(s: Any, allow_ulong: Literal[True] = ..., raise_on_error:
Literal[True] = ...) -> Union[symbol, ulong]:
    ...

@overload
def _check_type(s: _T, allow_ulong: bool = ..., raise_on_error:
Literal[False] = ...) -> _T:
-- 
Mit freundlichen Grüßen / Kind regards
Jiri Daněk

Reply via email to