Python Crossmodule Variables

Hello, I started a while ago a private python project. After some time of finding my way through the new language and the gui framework tkinter, I found an eventbus library.

I started to refactor my project to separate some stuff into modules and to think about a valuable use of the found library. But where to store the central eventbus? It should be available from every module, so let us try some stuff.

Example code

Module A
class Wrapper:
    def __init__(self, value):
        self.value = value

test_string = "A"
test_integer = 1
int_wrapper = Wrapper(1)

Module B
from A import test_string, test_integer, int_wrapper

test_string = "B"
test_integer = 2
int_wrapper.value = 2

def printContent():
    print("B-String:" + test_string)
    print("B-Integer:" + str(test_integer))
    print("B-Object:" + str(int_wrapper.value))

Module C

from A import test_string, test_integer, int_wrapper
from B import printContent

print("C-String:" + test_string)
print("C-Integer:" + str(test_integer))
print("C-Object:" + str(int_wrapper.value))

Execute C
# B-String:B
# B-Integer:2
# B-Object:2
# C-String:A
# C-Integer:1
# C-Object:2

What happened?

We execute C and C imports variables from A and a function from B. B imports variables from A and changes them.

What I would expect first is, that A is loaded, than B last C. A defines the variables, B changes them and C shows the same outcome like B.

BUT the variables test_string and test_integer from A are imported by value, because strings and integer are immutable.

This is not the same for objects, objects are used with references. So if you want a global eventbus for all your modules it is no problem to store it in its own package like the “int_wrapper”.