Prohibit yield, yield from, await, walrus in aliases and bounds?
JelleZijlstra opened this issue · 4 comments
In 3.10, we made a change to disallow usage of yield
, yield from
, await
, and named expressions (walrus) in annotations if from __future__ import annotations
is active. The motivation is that these can have unexpected effects on the enclosing scope, e.g. making it a generator or binding new names.
I am not sure what the status of these is under PEP 649; I checked in with Larry about that.
I think we want to prohibit the same kinds of expressions in type aliases and bounds under PEP 695. There is no static typing use case for them, their runtime behavior would be confusing, and if we ever do get a use case, it's easy to drop the restriction.
Implemented this:
>>> type X = (yield)
File "<stdin>", line 1
SyntaxError: 'yield expression' can not be used within a type alias
>>> class F[T: (x:=3)]: pass
...
File "<stdin>", line 1
SyntaxError: 'named expression' can not be used within a TypeVar bound
I just noticed that the PEP already explicitly disallows assignment/walrus expressions in several contexts, though it neglects to mention TypeVar bounds. I will propose a change that also disallows the walrus in bounds, and disallows yield/yield from/await in the same contexts.
This sounds good to me. All of these forms are considered type checker errors, so pyright already flags them as such. I didn't think deeply about whether they should be syntax (compiler) errors as well. I think you make a good case here.
Proposed this to the SC and I think it won't be controversial, closing.