Pylance提示'restaurant'参数未访问报错原因排查咨询
Pylance抛出「参数'restaurant'未访问」报错的原因
这个提示是Pylance静态代码检查抛出的未使用参数警告,触发逻辑非常明确:
- 你定义的
update函数中,restaurant形参在函数内部从来没有被读取过 - 函数内你直接对
restaurant变量做了赋值操作,全程没有用到调用函数时传入的restaurant实参值,静态检查就会判定这个参数是多余的
代码附带的隐藏逻辑bug
不止是警告问题,你当前的写法本身不符合Python的变量作用域规则,运行后达不到预期效果:
Python中函数内部直接给变量赋值,只会修改函数内的局部变量,完全不会影响函数外部的全局变量。也就是说你在update里给restaurant、number_of_visits、stand_dev、mean赋的新值,在函数外根本不生效,最后plt.hist调用的还是最开始初始化的标量restaurant1,不是你在函数里生成的10万长度采样数组。
修复方式
方案1:移除无用参数(仅消除警告)
如果不需要读取传入的restaurant值,直接把restaurant从update的形参列表里删掉,调用函数时也不要传入对应参数,警告会直接消失。但这个方案解决不了局部变量不生效的逻辑问题。
方案2:用返回值传递更新后的变量(推荐,同时解决警告和逻辑bug)
把函数内计算得到的更新值通过return返回,调用时接收返回值替换外部变量,参考修正代码:
import numpy as np import random as rand import matplotlib.pyplot as plt # 未知餐厅评分的标准差 actual_restaurant1 = np.random.normal(loc = rand.randint(1,50), scale = rand.randint(1,10)) actual_restaurant2 = np.random.normal(loc = rand.randint(1,50), scale = rand.randint(1,10)) stand_dev1 = 100 stand_dev2 = 100 mean1 = 0 mean2 = 0 number_of_visits1 = 0 number_of_visits2 = 0 restaurant1 = np.random.normal(loc = mean1, scale = stand_dev1) restaurant2 = np.random.normal(loc = mean2, scale = stand_dev2) # 移除未使用的restaurant形参,返回所有更新后的值 def update(actual_restaurant, number_of_visits, stand_dev, mean): number_of_visits = number_of_visits + 1 stand_dev = (1 / 10000 + number_of_visits) ** (-1) mean = actual_restaurant restaurant = np.random.normal(loc = mean, scale = stand_dev, size = 100000) return restaurant, number_of_visits, stand_dev, mean if restaurant1 > restaurant2: restaurant1, number_of_visits1, stand_dev1, mean1 = update(actual_restaurant1, number_of_visits1, stand_dev1, mean1) elif restaurant2 > restaurant1: restaurant2, number_of_visits2, stand_dev2, mean2 = update(actual_restaurant2, number_of_visits2, stand_dev2, mean2) plt.hist(restaurant1, 100) plt.show()
内容的提问来源于stack exchange,提问作者Siddd
相关产品推荐
相关产品推荐

