Ale*_*hen 6 python type-hinting pycharm python-3.x
class A:
pass
class A1(A):
pass
class A2(A):
pass
def help_here(s: WHAT_SHOULD_I_TYPE_HERE ):
# How to hint this function that accepts list,
# where all elements should be instances of same subclass of A.
# Example 1: [A1(), A1(), A1()] - good
# all components all elements are same class,
# and it is subclass of A
# Example 2: [A2(), A2(), A2(), A2()] - valid. Same reason.
# Example 3: [A1(), A1(), A2()] - invalid, not same classes.
# Example 4: [1, 2] - invalid. Same class, but not subclass of A.
if isinstance(s[0], A1):
# If I use Union[List[A1], List[A2]] as type hint,
# next line will have no warnings.
# But if where will be List[A] then warning arrives:
# Expected type 'List[A1]', got 'List[A]' instead.
# It's Pycharm IDE.
process_a1_list(s)
def process_a1_list(lst: List[A1]):
pass
def another_test():
# This is just to see, whether IDE will show warnings or not:
# No warning should be on this block
good_list: List[A1] = []
help_here(good_list)
# On both next calls IDE should warn
bad_list_1: List[A] = []
help_here(bad_list_1)
bad_list_2: List[int] = []
help_here(bad_list_2)
Run Code Online (Sandbox Code Playgroud)
我唯一的想法是:Union[List[A1], List[A2]]。
但是如果我不知道 的所有子类怎么办A?
有什么漂亮的方式来暗示吗?
更新:不太漂亮,但让 IDE (Pycharm) 按照我想要的方式检查类型。
Update2:我需要 IDE 类型提示解决方案而不是运行时检查。我不确定我想要的解决方案是否存在。
Python 3.8
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |