I have a project with project with several files for one I declare one variable as None and then inside a function I update it's value.
module_1.py
import pandas as pd
df_data = None
def read_files():
global df_data
df_data=pd.read_xlsx('dummy.xlsx')
module_2.py
from module_1 import df_data
from module_1 import read_files
read_files()
print(df_data)
# This returns None
I thought that being a global variable it would update even after importing because from module_1.py file I'm updating its value. But its none.
I think its because python imports the module initially with the value None, and even if set as global it won't reload the value.
I could do a get function, but is there any other way?
What's the correct way to do this? Make a get function and return the object itself? Is there any way to refresh variables after importing them?
TLDR: change the from import in module_2
import module_1
from module_1 import read_files
read_files()
print(module_1.df_data)
Explanation: your from module_1 import df_data creates a reference in the scope of module_2 to df_data from module_1. In your read_files() function you replace the value of df_data in the global scope of module_1, but this (as you figured it out) doesn't change anything in the scope of module_2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With