-
I'm trying to convert from using "mypy" to "pyright" to type-check a project (to be able to use ParamSpec), and I'm running into some snags making "pyright" happy with the code even after getting "mypy" to run cleanly. In particular, is there an equivalent to mypy's "allow_redefinition" in pyright? There are times when I couldn't get "mypy" to figure out that the type of a variable had been narrowed in the code, and so I would add explicit redefinitions to the narrower type when needed to give the type checker some help. However, I don't see an option like that in pyright, and when I try I get back an error about the parameter declaration obscuring a previous declaration of the same name. Also, there are places where mypy seems to be better at figuring things out on its own. For instance, I had a block which looked something like: from typing import Optional, Union
_DEFAULT_PATH = 'abc'
class FooTransport:
pass
class BarTransport:
def __init__(self, path: str):
self._path = path
def foo(path: Optional[str]):
transport: Union[None, FooTransport, BarTransport] = None
if not path:
try:
transport = FooTransport()
except OSError:
path = _DEFAULT_PATH
if not transport:
transport = BarTransport(path) With mypy, it was able to figure out that path became a
Without being able to manually redefine the type of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
I don't think it's safe for a type checker to assume that If you are sure that your logic is sound and there's no way for if not path:
try:
transport = FooTransport()
except OSError:
path = _DEFAULT_PATH
assert path is not None |
Beta Was this translation helpful? Give feedback.
I don't think it's safe for a type checker to assume that
path
is narrowed to astr
after the firstif
block. If noOSError
exception is raised,path
will retain its value ofNone
.If you are sure that your logic is sound and there's no way for
path
to retain itsNone
value at the end of the firstif
statement, then I recommend adding an assert statement to verify this assumption. This will also tell pyright about your assumption and allow it to apply the type narrowing.