Typing: Union changes break existing code

Created on 16 Oct 2017  路  3Comments  路  Source: python/typing

Summary

While I can see the argument for making it "not a type" in Python 3.6 the current changes mean it doesn't behave as an object either.

The problem

The problem is that Union[...] _is still_ a type, just with some non-standard overloads. This

  • is confusing
  • breaks existing code
  • leaves us with no way of identifying a Union because it acts neither like a proper class nor a proper object.

I would prefer a less-engineered solution that saw annotations as either a de-facto class or de-facto object.

Example

Retrieve the annotation "a" on a parameter "p", hence "a = Union[int, str]"

isinstance(a, Union) -> TypeException

Given the mantra, "Union is not a class", this is fine, I can't do isinstance(a, "eggs") either, so what _class_ should I check for:

type(a) --> typing.Union

This unfortunately takes us back to step 1.

Run-time checkers could previously use hasattr(a, "__union_params__"), however this has been removed, Union is now a Generic, which is a type, only it won't behave like one.

Most helpful comment

The typing module has provisional status, so it is not covered by the high standards of backward compatibility (although we try to keep it as much as possible), this is especially true for (yet undocumented) dunder attributes like __union_params__. If you want to work with typing types in runtime context, then you may be interested in the typing_inspect project (part of which may end up in typing later).

All 3 comments

But this works:

a = Union[int, str]
print(a.__args__)

This prints

(<class 'int'>, <class 'str'>)

The typing module has provisional status, so it is not covered by the high standards of backward compatibility (although we try to keep it as much as possible), this is especially true for (yet undocumented) dunder attributes like __union_params__. If you want to work with typing types in runtime context, then you may be interested in the typing_inspect project (part of which may end up in typing later).

I don't see any possible action item here, also get_args() got in typing in Python 3.8, so I think this can be closed now.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

matthiaskramm picture matthiaskramm  路  6Comments

LiraNuna picture LiraNuna  路  7Comments

gvanrossum picture gvanrossum  路  8Comments

feluxe picture feluxe  路  8Comments

zsluedem picture zsluedem  路  3Comments