'Mypy typing errors when upgrading to Twisted 21.2.0
In trying to upgrade the Twisted package from 20.3.0 to 21.2.0.
After the upgrade, when running Mypy I'm getting the following errors when accessing the reactor (from twisted.internet import reactor):
error: Module has no attribute "run" [attr-defined]
error: Module has no attribute "running" [attr-defined]
error: Module has no attribute "running" [attr-defined]
error: Module has no attribute "callLater" [attr-defined]
error: Module has no attribute "callInThread" [attr-defined]
error: Module has no attribute "callFromThread" [attr-defined]
error: Module has no attribute "spawnProcess" [attr-defined]
error: Module has no attribute "spawnProcess" [attr-defined]
When running Mypy with reveal_type(reactor):
Revealed type is '_importlib_modulespec.ModuleType'
I'm trying to understand what is the best way to handle this situation without just ignoring the errors so I can have the type checking when using the reactor.
Is there a better way to import the reactor? Is there a way to mark the type of the reactor for Mypy? should I cast it to a type every time before using it?
Solution 1:[1]
This seems to be an assigned bug in Twisted (https://twistedmatrix.com/trac/ticket/9909) and the proposed fix sounds like a breaking change.
One of the comments on their Trac describes casting it, as you suggest, as a workaround:
from typing import cast
import twisted.internet.reactor
from twisted.internet.interfaces import IReactorCore
reactor = cast(IReactorCore, twisted.internet.reactor)
reactor.run()
Solution 2:[2]
It took a ridiculous amount of searching but I finally found the solution in the Twisted source code itself. Add the following comment to the end of your line:
# type: ignore[attr-defined]
for example:
reactor.callFromThread(reactor.stop) # type: ignore[attr-defined]
That will "fix" it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cpmsmith |
| Solution 2 | JBCP |
