我有一个python字典的实例作为全局变量。我只在代码开头为其分配一个值。有时dict.get()
返回正确的对象,有时返回None。我找不到它的图案。
该代码是一个Web客户端,它等待HTTP请求并发送响应。我初始化了一个字典active_games
,以保留游戏列表,其中的键是服务器上的游戏ID。调用start()
时,会将游戏对象添加到词典中,直到调用end()
时才将其删除。在这两者之间,move()
被调用多次(通常每秒被调用多次)。 move()
中的print语句有时会打印正确的字典,有时会打印一个空的字典,然后引发错误。
以下是代码的相关部分:
import json
import os
import bottle
from api import ping_response, start_response, move_response, end_response
from game import game
# Store all games running on server
active_games = dict()
@bottle.post('/start')
def start():
global active_games
data = bottle.request.json
new_game = game(data["game"]["id"])
active_games[str(data["game"]["id"])] = new_game
print(active_games)
return new_game.start(data)
@bottle.post('/move')
def move():
global active_games
data = bottle.request.json
print(active_games)
return active_games.get(str(data["game"]["id"])).move(data)
@bottle.post('/end')
def end():
data = bottle.request.json
game_ending = active_games.pop(data["game"]["id"])
return game_ending.end(data)
为什么dict.get()不起作用?谢谢你的帮助!我可以编辑以添加日志和堆栈跟踪,如果有帮助的话
查看您发布的代码片段,我认为这与global active_games
和start()
方法中的end()
行有关。
“ global关键字用于从非全局范围(例如在函数内部)创建全局变量。”([https://www.w3schools.com/python/ref_keyword_global.asp,最后一次调用于02.11.2020,w3cschools.com-> Python教程-> Python全局关键字->定义和用法)
但是您不需要在这些函数中声明您的active_games字典,因为您已经在脚本的开头就已经声明了它们,就像这样
# Store all games running on server
active_games = dict()
所以global active_games
所做的就是用相同的名称覆盖您的active_games字典带有空变量,这是您的None返回值所来自的位置。
根据您的问题描述,这可能不是幕后情况,但是您至少可以做的是从代码中删除global active_games
的所有实例,然后再与我联系