In the examples above, yes. There could be other categories in the other examples.It looks like there's two different categories of inputs: a serialized format (json, ip address, arg parsing, struct unpacking) and float pow operator?
TBH, I don't see how a function accepting a serialized input that decodes to different output types could safely use this AnyOf concept. The example that springs to mind is JSON decoding, which IME frequently has unexpected values (untrusted user input; old/inconsistent data format (e.g. "date" was encoding as int timestamp, then later switched to ISO timestamp); etc), which causes problems much later on (call stack or calendar wise) in some unrelated code. But, fundamentally, the same is true for the other examples.
AnyOf is not safe, but it is safer than the status quo. For example, the following type errors are currently accepted, but could be caught with AnyOf:
j = json.loads(...)
j.get(12)
j.gets("foo")
def foo(x: Mapping[int, Any]) -> None: ...
foo(j)
This has been debated before and the current consensus for typeshed is not to use safe unions in return types (with exceptions). This proposal is supposed to improve on that status quo. Generally, typeshed prefers false negatives over false positives, which is especially necessary to ease the transition burden.IME, manually narrowing a union is easy: assert with isinstance(). It's cheap, easy, and detects the failure at the point of origin.
For float pow -- and I don't recall the exact API definitions -- isn't it well defined (I couldn't find the language def from a quick search)? i.e if any input arg is complex, then the output is complex.
Yes, but e.g. (-2) ** -0.5 also returns a complex number.
- Sebastian