PyCharm中Streamlit代码出现object类属性引用未解析问题求助
问题解决:PyCharm中Streamlit项目的属性引用错误
错误原因
PyCharm的静态类型推断无法正确识别np.unique(...).tolist()返回的列表类型,误将country变量判定为object类型,因此抛出Unresolved attribute reference错误。而years变量由pandas Series的unique().tolist()生成,PyCharm对其类型推断更准确,所以无异常。
另外你的代码存在一个隐藏bug:years = years.insert(0, 'Overall')中,list.insert()是原地修改列表,返回值为None,执行这行后years会被赋值为None,后续使用会引发错误。
解决方法
方法1:显式类型注解
给country变量添加类型注解,明确告诉PyCharm它是列表类型:
import numpy as np def country_year_list(df): years = df['Year'].unique().tolist() years.sort() years.insert(0, 'Overall') # 去掉赋值,insert原地修改 # Create a list of countries country: list = np.unique(df['region'].dropna().values).tolist() # Sort the list country.sort() # Insert a new item at the beginning of the list country.insert(0, 'Overall') return years, country
方法2:用list()包裹转换
改用list()直接转换np.unique的结果,让PyCharm更易识别类型:
import numpy as np def country_year_list(df): years = df['Year'].unique().tolist() years.sort() years.insert(0, 'Overall') # 修复赋值bug # Create a list of countries country = list(np.unique(df['region'].dropna().values)) # Sort the list country.sort() # Insert a new item at the beginning of the list country.insert(0, 'Overall') return years, country
方法3:临时忽略提示(不推荐)
如果不想修改代码,可点击错误提示旁的灯泡图标,选择Suppress for statement暂时屏蔽该警告,但这只是规避问题而非彻底解决。
内容的提问来源于stack exchange,提问作者Prince Chaudhary
相关产品推荐
相关产品推荐

