Type narrowing with inner functions #2332
decorator-factory
started this conversation in
Ideas
Replies: 1 comment
-
Even if pyright assumed const semantics, it would still need to perform code flow analysis of the outer scope and "guess" where in the code flow the inner function was called. This can't be determined in the general case. Consider the following: def call_something(func: Callable[[], AsyncIterator[bytes]]) -> AsyncIterator[bytes]:
return func()
class Storage:
async def find(self, key: str) -> Optional[AsyncIterator[bytes]]:
content = self._files.get(key)
async def _find() -> AsyncIterator[bytes]:
yield content
call_something(_find)
if content is None:
return None
return call_something(_find) The workaround I suggest here is to use a new temporary variable whose type is known not to be async def find(self, key: str) -> Optional[AsyncIterator[bytes]]:
content = self._files.get(key)
if content is None:
return None
validated_content = content
async def _find() -> AsyncIterator[bytes]:
yield validated_content |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I was wondering why this says "Never":
I read #851 and it made sense.
I was trying to make this work:
Pyright is saying that
content
could beNone
. I found an explanation in #599 and #1731 but found it strange that it behaves like this.I wondered if TypeScript behaved the same but it didn't: (TypeScript playground)
However, if you change
const value
tolet value
, TypeScript does what pyright does. Would it be possible for pyright to have typescript'sconst
semantics if it knows that there's only one assignment?Beta Was this translation helpful? Give feedback.
All reactions