简体   繁体   English

全局变量在不同的函数中是不同的

[英]global variable is different in different functions

I know that using global variable in functions is wrong, but I have a code that uses these variables and I have an issue that I can't find how to solve. 我知道在函数中使用全局变量是错误的,但是我有一个使用这些变量的代码,但有一个我找不到解决方法的问题。

I have a module with the following code: 我有一个包含以下代码的模块:

messages = {}

def MessageReceived(message):
    global messages

    print messages
    msgNumber = message[0]
    if messages.has_key(msgNumber):
        messageData = messages.pop(msgNumber)
        ReleaseMessageNumber(msgNumber)
        if messageData["callback"] is not None:
            messageData["callback"](messageData["originalMessage"])

def SendMessage(message, callBack):
    global messages

    msgNumber = GetMessageNumber()

    messageToSend = msgNumber + message + "\0"

    messages[msgNumber] = { 'originalMessage' : message, 'time' : time.time(), 'callback' : callBack }
    print messages
    Send(messageToSend)

    return True

In general, the function "SendMessage" builds a message with a message number, sends the message an stores the message and a callback in a global dictionary. 通常,函数“ SendMessage”构建带有消息号的消息,向消息发送并在全局字典中存储消息和回调。

The function "MessageReceived" gets the callback of the specific message from the global dictionary and calls it. 函数“ MessageReceived”从全局词典中获取特定消息的回调并进行调用。

The problem is that it seems that 2 different dictionaries exists here. 问题在于,这里似乎存在两个不同的字典。

When I send a message, I see that the dictionary grows (a new record is added to the dictionary every time I send a message), but the print at the "MessageReceived" function always shows an empty dictionary. 当我发送一条消息时,我看到字典在增长(每次发送一条消息时都会向字典中添加一条新记录),但是“ MessageReceived”功能的打印内容始终显示一个空字典。

Can you help me with that? 你能帮我吗? Where is the bug here? 错误在哪里?

Thanks! 谢谢!

Firstly, although it doesn't affect your problem there is no need to use the global keyword anywhere in this code. 首先,尽管它不会影响您的问题,但无需在此代码的任何位置使用global关键字。 You never re-assign the global dicts, you only mutate them, so there is no need to declare them as global - Python finds them in the module scope anyway. 您永远不会重新分配全局dict,只对它们进行突变,因此无需将它们声明为全局-Python无论如何都会在模块范围内找到它们。

The problem though is that all module-level variables are per-process. 问题是所有模块级变量都是按进程的。 If your receive function is always running in its own thread, it will never see any of the data from the view. 如果您的receive函数始终在其自己的线程中运行,则它将永远不会从视图中看到任何数据。

Since however you already know that using global variables is bad, I'm not sure why you are doing it. 但是,由于您已经知道使用全局变量是不好的,所以我不确定为什么要这样做。 There are plenty of ways of passing data between processes; 有很多方法可以在进程之间传递数据。 storing it in the database is probably the best if you're using Django. 如果您使用的是Django,最好将其存储在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM