如何修复Pylance提示的‘get is not a known member of None’字典问题
解决Pylance提示“get is not a known member of None”问题
问题原因
request.json并非总能返回字典对象——当请求未携带合法JSON数据时,它会返回None。Pylance通过静态类型检测发现json_data可能为None,因此提示调用get方法存在风险。
解决方案
方案1:先校验json_data有效性再调用方法
在使用json_data的get方法前,先判断它是否为None,避免非法调用:
def validate_amount(): try: json_data = request.json def isfloat(num: str) -> bool: try: float(num) return True except ValueError: return False # 先判断JSON数据是否有效 if json_data is None: response = "Invalid JSON data" else: amount_val = json_data.get('amount','0.0') amount_in_words = json_data.get('amount2words','') if isfloat(amount_val): split_amt = amount_val.split('.') response = split_amt except Exception as e: response = f'An Error Occurred - {e}'
方案2:将None转为空字典
通过or运算符把None转为空字典,这样即使request.json返回None,也能安全调用get方法:
from typing import Dict, Optional def validate_amount(): try: json_data: Optional[Dict] = request.json # 若json_data为None则替换为空字典 json_data = json_data or {} def isfloat(num: str) -> bool: try: float(num) return True except ValueError: return False amount_val = json_data.get('amount','0.0') amount_in_words = json_data.get('amount2words','') if isfloat(amount_val): split_amt = amount_val.split('.') response = split_amt except Exception as e: response = f'An Error Occurred - {e}'
方案3:类型断言(谨慎使用)
如果能确保请求一定携带合法JSON数据,可以用类型断言告诉Pylancejson_data是字典类型,跳过类型检查:
def validate_amount(): try: json_data = request.json # 类型断言,明确告知Pylance这是字典类型 json_data = json_data # type: dict def isfloat(num: str) -> bool: try: float(num) return True except ValueError: return False amount_val = json_data.get('amount','0.0') amount_in_words = json_data.get('amount2words','') if isfloat(amount_val): split_amt = amount_val.split('.') response = split_amt except Exception as e: response = f'An Error Occurred - {e}'
注意:这种方式会忽略Pylance的类型提示,如果实际运行中json_data为None,仍会触发运行时错误,仅适用于请求JSON数据必然存在的场景。
内容的提问来源于stack exchange,提问作者VijayaDurgaPrasad
相关产品推荐
相关产品推荐

