You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyomo中__getitem__弃用警告问题及解决方案咨询

Pyomo弃用警告问题解答

问题背景

我在使用Pyomo时编写了如下代码:

outputVariables_list = [model.param1, model.variable1]
optimal_values_list = [[pyo.value(model_item[key]) for key in model_item] for model_item in outputVariables_list] 

运行时触发弃用警告:

WARNING: DEPRECATED: Using __getitem__ to return a set value from its
    (ordered) position is deprecated.  Please use at()  (deprecated in 6.1,
    will be removed in 7.0)

尝试改用at()方法却出现报错,比如使用pyo.at(model_item[key])、pyo.value(model_item.at[key])等写法均报错。我的输出列表包含参数、变量和集合,如outputVariables_list_BT2中的组件。

现有两个疑问:

  1. 为何Pyomo推荐使用at()替代__getitem__,但实际使用却报错?
  2. 由于我的集合(timeslots)有自然顺序,当前结果符合预期,暂不升级Pyomo到7.0,能否屏蔽该警告?

解答

1. at()使用报错的原因

Pyomo的at()是集合(Set)专属方法,仅用于通过索引位置获取集合元素,正确用法是用圆括号调用:model.timeslots.at(0)(获取集合第一个元素)。而你的遍历列表包含参数(Param)、变量(Var)这类非集合组件,它们本身没有at()方法,直接统一调用自然会报错。

原警告仅针对集合用__getitem__按位置索引的场景,并非参数/变量的键索引操作。你的代码中如果是集合组件触发了警告,只需单独对集合类型的model_item改用at(),参数和变量仍保留原pyo.value(model_item[key])写法即可。

2. 屏蔽弃用警告的方法

可以通过Python的warnings模块精准屏蔽该警告,代码如下:

import warnings
from pyomo.common.deprecation import PyomoDeprecationWarning

# 定向屏蔽目标警告
warnings.filterwarnings(
    "ignore",
    category=PyomoDeprecationWarning,
    message=r"Using __getitem__ to return a set value from its \(ordered\) position is deprecated"
)

这段代码只会屏蔽你遇到的这条特定警告,不会影响其他Pyomo或系统警告。


内容的提问来源于stack exchange,提问作者PeterBe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:52:26