我有一个单独的python字典实例作为全局变量。我只在代码的开头给它赋值。有时dict.get()
返回正确的对象,有时返回None。我找不到它的模式。
代码是一个等待HTTP请求并发送响应的web客户端。我初始化了一个名为active_games
的字典来保存游戏列表,其中的键是来自服务器的游戏ids。调用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()不能工作?谢谢你的帮助!如果有帮助,我可以编辑以添加日志和堆栈跟踪
发布于 2020-02-11 18:34:00
看一下您发布的代码片段,我认为它与start()
和end()
方法中的global active_games
行有关。
“全局关键字用于从非全局作用域创建全局变量,例如在函数内部。”(https://www.w3schools.com/python/ref_keyword_global.asp,最后一次调用是在2020年2月2日,w3cschools.com -> Python Tutorial -> Python全局关键字->定义和用法)
但是您不需要在这些函数中声明您的active_games字典,因为您已经在脚本的开头声明了它们,如下所示
# Store all games running on server
active_games = dict()
因此,global active_games
所做全部工作就是使用同名的空变量覆盖您的active_games字典,这就是None返回值的来源。
从您的问题描述可以看出,这可能并不是幕后发生的事情,但您至少可以从代码中删除任何global active_games
实例,然后再与我联系
https://stackoverflow.com/questions/60175011
复制相似问题