classification
Title: Union of a type and the typing module function
Type: Stage:
Components: Interpreter Core Versions: Python 3.11, Python 3.10
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: gvanrossum, kj, serhiy.storchaka
Priority: normal Keywords:

Created on 2021-07-15 07:58 by serhiy.storchaka, last changed 2021-07-16 15:13 by gvanrossum.

Messages (5)
msg397528 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021-07-15 07:58
The union type accepts any function from the typing module:

>>> import typing
>>> int | typing.cast
int | typing.cast
>>> int | typing.get_type_hints
int | typing.get_type_hints

It is a consequence of too lenient check for the typing.NewType() result (which does not work at all with PR 9951).
msg397558 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2021-07-15 15:14
Is it worth being picky about this? The internal data structures are safe. A static checker will complain. What more do you need?
msg397569 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021-07-15 16:47
It is only reminder that our test for NewType is arbitrary. And it is not compatible with PR 9951. Possible solutions are:

1. Make NewType a class and add more strict test. Pro -- we can make arbitrary repr, contra -- it has small negative effect on performance. See issue34963.

2. Remove the test for NewType at all and allow or-ing types and arbitrary functions.

3. Introduce a special attribute to distinguish unionable objects. It will make the code of unionobject.c simpler.

I lean towards option 1 (not excluding 3). Small performance losses seem inevitable.
msg397570 - (view) Author: Ken Jin (kj) * (Python committer) Date: 2021-07-15 16:56
@Serhiy
> 1. Make NewType a class and add more strict test.

See also: issue44353 (https://bugs.python.org/issue44353). We had some discussion there about converting to class but it ended in a deadlock.
msg397632 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2021-07-16 15:13
I think making NewType into a class isn't a good idea, it would be too slow. But I like issue34963 (PR 9951).

So then let's do some variation on (3) -- unionable things would include all types (of course), typevars, and things that have a special attribute. We could then set that special attribute on the function returned by NewType (like PR 9951 already does for __name__ and __qualname__).

What to call it? Maybe "__unionable__"?
History
Date User Action Args
2021-07-20 01:32:57kjlinkissue44353 superseder
2021-07-16 15:13:51gvanrossumsetmessages: + msg397632
2021-07-15 16:56:07kjsetmessages: + msg397570
2021-07-15 16:47:27serhiy.storchakasetmessages: + msg397569
2021-07-15 15:14:43gvanrossumsetmessages: + msg397558
2021-07-15 07:58:18serhiy.storchakacreate