Skip to main content
 首页 » 编程设计

python之为什么 pylint 告诉我我的 dict 属性是一个 undefined variable

2025年05月04日21rubylouvre

我正在使用为 python 3+ 配置的 pylint 处理这段代码:

import utils 
 
valid_commands = ['category', 'help', 'exit'] 
 
def createCategory(): 
    utils.clear() 
    category = { 
        name: 'test' <- allegedly undefined 
    } 
    utils.insertCategory(category) 
 
def listActions(): 
    utils.clear() 
    for command in valid_commands: 
        print(command) 
 
def exit(): 
    utils.clear() 
 
actions = { 
    'category': createCategory, 
    'help':     listActions, 
    'exit':     exit 
} 
 
command = '' 
while command != 'exit': 
    command = input('task_tracker> ') 
    if command in valid_commands: 
        actions[command]() 

我收到这个错误:

我的代码运行良好,但这个错误不会消失的事实让我抓狂。为什么它告诉我这是未定义的?

请您参考如下方法:

字典键应该是一个不可变值,或者是一个包含不可变值的变量(如字符串或数字)。 name 不是字符串,也没有定义为当前范围内的变量。解决这个问题的一种方法是

def createCategory(): 
    utils.clear() 
    category = { 
        'name': 'test' 
    } 
    utils.insertCategory(category)