英文:
Appease mypy where None is type hinted and other operands are used
问题
以下是翻译好的部分:
我有两段代码,其中默认值可能为None,但是在操作(>)或列表迭代之前会捕获None值。尽管我看不出在任何情况下None会通过,但Mypy仍然会产生错误消息。
在这两种情况下,Mypy都会报错。
第一段代码:
Item "None" of "Optional[List[str]]" has no attribute "__iter__" (not iterable) [union-attr]
第二段代码(多个类似的错误):
Unsupported operand types for > ("float" and "None") [operator]
有没有更好的编写方式或更Pythonic的方法?还是我应该忽略Mypy的错误?
希望这可以帮助您理解问题并采取适当的措施。
英文:
I have 2 pieces of code where default values could be None, but the None values are caught before the operation (>) or iteration of a list. Mypy is still producing an error message despite the fact that I can't see how None could get through in either case.
def plot_columns(df: pd.DataFrame, columns: list[str] | None = None):
if not columns:
columns = df.columns
for col in columns:
plt.plot(df[col])
def function_2(tup: tuple[float | int | None, float | int | None]) -> bool:
assert len(tup) == 2
if all(tup): # Also tried: if tup.count(None) == 0
return tup[0] > tup[1]
return False
In both cases mypy throws errors
first: Item "None" of "Optional[List[str]]" has no attribute "__iter__" (not iterable) [union-attr]
second (multiple similar errors): Unsupported operand types for > ("float" and "None") [operator]
Is there a better way to write these or a more pythonic way to do it? Or should I just ignore mypy on this one?
Edit: Appeased the first one by making it an empty list.
答案1
得分: 1
For the first one:
对于第一个问题,`pandas` 似乎没有对 `df.columns` 进行类型标注,因此无法在静态分析中确定该值不是 `None`。尝试使用以下方式:
```python
def plot_columns(df: pd.DataFrame, columns: list[str] | None = None):
if not columns:
columns = cast(list[str], df.columns)
...
For the second one:
对于第二个问题,`all(tup)` 似乎不在 `mypy` 认可的类型缩小表单列表中。(或者说,类型缩小允许你缩小 `tup` 本身的类型,而不是 `tup` 中的元素类型。)需要更加明确:
```python
def function_2(tup: tuple[float | int | None, float | int | None]) -> bool:
assert len(tup) == 2
a, b = tup
if a is None or b is None:
return False
return a > b
英文:
For the first one, pandas
itself doesn't seem to have typed df.columns
so that you can tell statically that the value is not None
. Try
def plot_columns(df: pd.DataFrame, columns: list[str] | None = None):
if not columns:
columns = cast(list[str], df.columns)
...
For the second one, all(tup)
doesn't seem to be on mypy
's list of recognized forms for type narrowing. (Or, type narrowing lets you narrow the type of tup
itself, not the elements of tup
.) Be more explicit:
def function_2(tup: tuple[float | int | None, float | int | None]) -> bool:
assert len(tup) == 2
a, b = tup
if a is None or b is None:
return False
returnn a > b
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论