Skip to content

Instantly share code, notes, and snippets.

@luckydonald
Created October 12, 2021 14:57
Show Gist options
  • Save luckydonald/0d024a641469693e2cfcf916cc91fdf2 to your computer and use it in GitHub Desktop.
Save luckydonald/0d024a641469693e2cfcf916cc91fdf2 to your computer and use it in GitHub Desktop.
tg-2021-10-12_16-57-25.md

Before:

NONE_TYPE = type(None)
union_params = type_hint.__args__   # this was __union_params__ in python3.5, but __args__ in 3.6+

assert union_params
is_optional = NONE_TYPE in union_params
if len(union_params) == (2 if is_optional else 1):
    # None is the first/second one, the actual type has to be the other.
    raise ValueError('MEhhhh')
# end if
the_type = 0 if not is_optional and union_params.index(NONE_TYPE) == 1 else 1

After:

NONE_TYPE = type(None)
union_params = type_hint.__args__   # this was __union_params__ in python3.5, but __args__ in 3.6+

match union_params:
    case [NONE_TYPE, the_type] | [the_type, NONE_TYPE]:
        is_optional = True
    case [the_type]:
        is_optional = False
    case something_else:
        raise ValueError('MEhhhh')
# end match
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment