Abstract
Add a way to annotate the class Any itself.
I addressed this here:
And before that in this StackOverflow post:
Motivation
Currently there is no way in the type system to annotate a variable that holds the class Any. Any is a special form in the type system and therefore it behaves in a special way for type checkers. From the docs:
Therefore, when type[Any] is specified, it doesn’t mean the class Any itself, but any object that is a class.
This leaves us with the exceptional case that the class Any itself cannot be perfectly typed if stored in a variable.
This is not a very common problem, but when needed it is impossible to solve elegantly in the current type system.
Subclasses of Any are not affected, nor instances of them. Any itself cannot be instantiated, therefore typing instances of Any is not a required functionality either.
Specification
There are 3 possible ways to implement this:
- Make
_AnyMetapublic and usable from outside in type annotations - Add an alias for
_AnyMetacalledAnyType, similar toEnumMetaandEnumType - Allow the use of
Literal[Any]to mean the classAny
Backwards Compatibility
No breaking changes.
Security Implications
None.
How to Teach This
When learning how to use Any, the programmer quickly learns that it has special meanings. When they need to type the class Any itself, they might themselves realize that in the typical way, it isn’t possible. They will then learn about the introduced feature.
Reference Implementation
Depending on the implementation either:
- Make the
_AnyMetaclass public and rename/alias it - Create an alias to
_AnyMeta - Make type checkers not error when
Anyis used inside ofLiteraland give it the special meaning explained above
Rejected Ideas
In the linked topic, another alternative was suggested, but it is worse and not acceptable:
The idea was to (ab)use the (likely to be added) 3.15 feature TypeForm to express the class Any. TypeForm[Any] would annotate the class Any, while TypeForm would annotate any type.
This is not the preferred solution, because TypeForm should act as an extension of type to annotate types instead of just classes. Because type and type[Any] mean the same thing, it would be confusing to have TypeForm and TypeForm[Any] mean something different.
Open Issues
Decide which solution of the 3 proposed is the best. Other ideas are welcomed of course.
Acknowledgements
All people from the StackOverflow post and the TypeForm topic who repsonded and gave their ideas and opinions.
Footnotes
None.
Copyright
This document is placed in the public domain or under the
CC0-1.0-Universal license, whichever is more permissive.
Edits: Fix bad grammar, improve the title, replace placeholder of “reference implementation” and more minor fixes…