简体   繁体   中英

Sharing variables across modules

I have a program- main.py that generates values for a few parameters depending on the user provided inputs. I need to share these variables with other modules- aux.py . To do that I did the following (simplified code below) -

This the main.py file:

# these three variables are dynamically calculated depending on the user provided input
a = 12
b = 13
c = 14

def declare_global():
    global a, b, c

declare_global()
import aux
aux.print_all()

This is the aux.py file

def print_all():
    a = globals()['a']
    b = globals()['b']
    c = globals()['c']
    print(a)
    print(b)
    print(b)

Running the main.py file results in the following error

Traceback (most recent call last): File "/Users/new/Library/Preferences/PyCharmCE2018.3/scratches/global_experiment/main.py", line 13, in aux.print_all() File "/Users/new/Library/Preferences/PyCharmCE2018.3/scratches/global_experiment/aux.py", line 2, in print_all a = globals()['a'] KeyError: 'a'

There is a very similar post addressing the same issue here but the posts there suggest adding all global variables to a new file and then importing the created file. But I cannot do that as I'll have no prior information as to what values these variables will take.

So, how do I share variables across modules?

EDIT

I lost some complexity of the actual program in order to make a minimalistic example. The reason I cannot pass the variables a,b,c to the print_all function is because in the actual program, the variables a,b,c are not serializable. They are spark dataframe objects. And one of the modules I use there (which here I am representing by print_all ) serializes all its inputs I end up with an error (spark dataframes aren't serializable). Using a few workarounds I have arrived here where I use global variables and no inputs to the functions.

a = 12
b = 13
c = 14

import aux
aux.print_all(a, b, c)

Then your aux file will become:

def print_all(a, b, c):
    a = globals()['a']
    b = globals()['b']
    c = globals()['c']
    print(a)
    print(b)
    print(b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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