Closed snazzyfox closed 11 months ago
The system was implemented before typing had really matured much, it's probably due for a bit of a facelift to keep it afloat until we can redesign the thing for our next release cycle. I'll take a closer look into some of the common typing features tomorrow, but due to our support of 3.7, some of the newer ones might not be fully implementable.
I see! Both Optional and typing.Union exists in python3.7, and they both generate the exact same typing._UnionGenericAlias
object, so they can probably be handled together.
The pipe syntax (since python3.10) generates an object of a different type, so it'll probably need some special handling. It creates a types.UnionType
object instead, which does not exist in versions before 3.10. Maybe skip this check if its import errors?
For my issue at hand, I'll also understand if the scope of this issue gets limited to supporting only Optional
(ie unions of exactly one concrete class and None), instead of any arbitrary unions. That way, the parsing logic can stay put; the only addition would be to strip off the Optional
from Optional[T]
if the type is such, which also means it can be done at command creation time instead of during command handling.
Progress on this can be tracked on branch feature/union_parsing
Update: progress can now be tracked on #425
Description
It is not possible to use any typing constructs that's not directly a class as the type of an argument, due to the fact that twitchio uses the type annotation verbatim to initialize the object. This is often necessary as the default value for some arguments may need to be
None
.The only workaround to this is to use a single type which satisfies twitchio. This causes the function to (correctly) fail type checks.
Since an argument being optional is a common occurance, I think it's useful to support optional types, which in typing is represented as a union with None.
Example
This is valid Python typing construct:
When ran, this generates the stacktrace
The following are also valid and equivalent to the above:
Both of these generate similar stacktraces with the annotations printed verbatim:
The following works, but it is marked as a type error by static type checkers (because it does in fact violates typing safety).