簡體   English   中英

預提交/pylint:我的輸入可能有兩種類型,但在說明中沒有得到

[英]pre-commit/pylint : two types possible for my input, but it doesn't get that in the instructions

這是我到目前為止的代碼,但我的輸入可以是 boolean 或大小為 2 的列表(str 和 int)。 這是代碼的一部分:

        # In the function arguments
        structured: Union[List[bool], bool]
        grid: Union[List[bool], bool]
        
        # instructions
        if structured is False or grid is False:
            self.structured: bool = False
        else:
            self.structured = True
            self.eltType = structured[0]
            self.Lx = grid[0]
            self.Ly = grid[1]
            self.Lz = structured[1]

但我得到錯誤:

error: Value of type "Union[List[bool], Literal[True]]" is not indexable  [index]

問題是第一個 if 語句解決了 grid/structured 是 bool 的情況,而 else 是 arrays 的情況。

我的第二個問題是如何注釋包含 str 和 int 的數組。

List[Union[str,int]]  # maybe ?

如果您的條件為假,則不能出於類型縮小的目的保證任一變量都是列表,只是其中至少有一個等於False

使用更明確的條件:

self.structured: bool
if isinstance(structured, list) and isinstance(structured, list):
     self.structured = True
     self.eltType = structured[0]
     self.Lx = grid[0]
     self.Ly = grid[1]
     self.Lz = structured[1]
else:
    self.structured = False

由於True的值似乎對任何一個變量都沒有意義,因此請考慮使用更受約束的類型,例如Optional[list[bool]] 那么你只有None或一個(不一定足夠長)列表。

# In the function arguments
structured: Optional[List[bool]]
grid: Optional[List[bool]]
    
self.structured: bool
if structured is not None and grid is not None:
    # Both must be lists
    self.structured = True
    self.eltType = structured[0]
    self.Lx = grid[0]
    self.Ly = grid[1]
    self.Lz = structured[1]
else:
    # One of them might be a list, but we'll ignore it.
    self.structured: bool = False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM