Skip to content

Optional and other type tests in 3.6 Union #389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
hsolbrig opened this issue Feb 10, 2017 · 1 comment
Closed

Optional and other type tests in 3.6 Union #389

hsolbrig opened this issue Feb 10, 2017 · 1 comment
Labels
resolution: duplicate The idea/problem was already reported

Comments

@hsolbrig
Copy link

In 3.5, I was able to test for optional and parameter types by:

from typing import Union, Optional

def is_optional(t):
   return issubclass(type(None), t)

def is_valid(e, t):
   return issubclass(type(e), t)

is_optional(Union[int, str])
> False
is_optional(Union[int, str, None])
> True
is_valid("abc", Union[int, str])
> True
is_valid(["abc"], Union[int, str])
> False

The issubclass method is no longer allowed in 3.6. How do I accomplish the equivalent in 3.6 on?

@ilevkivskyi
Copy link
Member

ilevkivskyi commented Feb 10, 2017

In general, it is difficult to make runtime type checks reliable enough. This is why it was decided, to remove this functionality (and some other) in favour of static type checkers like mypy, pytype, etc. This also allowed to make typing module faster.

Instead, a set of tools is being developed now in #377 that will allow users to build efficiently their own runtime checks tuned to their specific needs. The set of tools will contain functions like is_union_type, is_generic_type, get_args, etc. For example, using such tools one could define:

from typing_inspect import is_union_type, get_args

def is_optional(tp):
    return is_union_type(tp) and type(None) in get_args(tp)

There was also a related discussion at http://bugs.python.org/issue29262

If you are interested in quick workarounds, then you could use the private typing API, but this is not recommended, for example something like:

import typing
def is_optional(tp):
    return type(tp) is typing._Union and type(None) in tp.__args__

@ilevkivskyi ilevkivskyi added resolution: duplicate The idea/problem was already reported question labels Feb 10, 2017
hsolbrig pushed a commit to hsolbrig/PyShExJ that referenced this issue Feb 12, 2017
Typing library is in a state of flux.  See [python inquiry](python/typing#389) Not tested with earlier versions at this point.
@srittau srittau removed the question label Nov 4, 2021
@srittau srittau closed this as completed Nov 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
resolution: duplicate The idea/problem was already reported
Projects
None yet
Development

No branches or pull requests

3 participants