Python键入有效的布尔组合
我正在尝试使用Python的类型检查器来捕获不兼容的权限。我有一个允许的情况,可以允许(布尔值)(布尔)(布尔值)进行特定的诉讼。显然,我想排除禁止和要求的情况,因为这是不可能的。
这是我尝试的。
Permissions = Union[
Tuple[Literal[False], Literal[False]], # forbidden and not required
Tuple[Literal[True], Literal[False]], # permitted and not required
Tuple[Literal[True], Literal[True]] # permitted and required
# (No option for forbidden and required)
]
forbidden: Permissions = (False, False)
allowed: Permissions = (True, False)
required: Permissions = (True, True)
mypy_should_catch: Permissions = (False, True)
我希望Mypy允许前三个,但禁止最后一个。
但是,我实际上得到的是所有四个错误的错误:
error: Incompatible types in assignment (expression has type "Tuple[bool, bool]", variable has type "Union[Tuple[Literal[False], Literal[False]], Tuple[Literal[True], Literal[False]], Tuple[Literal[True], Literal[True]]]")
如何使这项工作?
I'm trying to use Python's type checker to catch incompatible permissions. I have a permission situation where a particular action can be permitted (boolean) and required (boolean). Obviously, I want to rule out the situation where it is forbidden and also required, since this is impossible.
Here's what I have tried.
Permissions = Union[
Tuple[Literal[False], Literal[False]], # forbidden and not required
Tuple[Literal[True], Literal[False]], # permitted and not required
Tuple[Literal[True], Literal[True]] # permitted and required
# (No option for forbidden and required)
]
forbidden: Permissions = (False, False)
allowed: Permissions = (True, False)
required: Permissions = (True, True)
mypy_should_catch: Permissions = (False, True)
I expect mypy to allow the first three, but disallow the last.
However, what I actually get is an error like this for all four:
error: Incompatible types in assignment (expression has type "Tuple[bool, bool]", variable has type "Union[Tuple[Literal[False], Literal[False]], Tuple[Literal[True], Literal[False]], Tuple[Literal[True], Literal[True]]]")
How can I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Mypy 0.941确实只捕获最后一行:
因此,您只需要升级即可。
mypy 0.941 does catch the last line only:
So it looks like you just need to upgrade.
最后,我在尝试以类型安全的方式捕获禁止/允许/要求的逻辑方向略有不同。
但是,我不会将其标记为答案,因为仍然存在一个问题:为什么原始方法无法正常工作。
In the end I went a slightly different direction in trying to capture the logic of forbidden/permitted/required in a type-safe way.
However, I won't mark this as the answer as there's still the question of why the original approach didn't work as expected.