When developing an application, I found out that it is hard to persist variables across imports. Perhaps it would be easier to explain with an example:
# a.py
v = []
def add_to_v():
global v
v.append(1)
if __name__ == '__main__':
print(v)
# b.py
from a import add_to_v
add_to_v()
add_to_v()
Expected output: [1, 1]
. Actual output: []
.
I think that I can solve this problem by persisting the variable to a file, but there must be a more elegant solution. Why does this happen and how can I solve this problem elegantly without writing the variable to a file?