1

I want to share a variable between two scripts, and in one script, there's a calculation based on the variable dynamically. My use case is aiming for separating the concern on building a website, specifically, using streamlit. But, I would like to provide a simple example to explain what I am trying to do. I would only run app.py.

For example:

[app.py]

# get the input from the user
select = input("[Please choose A, B, or C]")
print(result)

[data.py]

# where I want to deal with data things
# such as making a query to Pandas data frame
result = df[df['choice']==select]['result'].values[0]

What I've found:

  1. If I import select and result to each other, it would be a circular import.
  2. I found the multiprocessing usage, sharing the variable between two scripts, but it seems to not be capable of solving the problem.

Is it possible to share a variable dynamically or sort of concurrently between files with any library? Please advise if my title or example could've improved. Thanks.

Woden
  • 1,054
  • 2
  • 13
  • 26
  • If I understand your question properly then in data.py you could just *import select from app*. Although in app.py you would need to pre-declare *select* e.g. *select = None* because otherwise it wouldn't exist at the import phase –  Sep 11 '21 at 07:16

2 Answers2

0

Python objects are accessed via references. Assuming you are not using static objects (e.g., int, float, str) anything that has that reference can read/mutate the associated object.

However, writing code that way with global references can lead to difficult to understand and debug code. You are better off having the object in one module and having a read/mutate API to make changes to it from other module(s).

ZaydH
  • 658
  • 6
  • 22
0

Don't try to share global variables between modules both ways, it goes against the very intent of modules as separate namespaces and as you have observed, causes a circular import error.

You already only want to run app.py, so it's fine to keep your globals in that namespace. You can still get data.py to do some work, you just need functions.

[app.py]

from data import make_result

# get the input from the user

select = input("[Please choose A, B, or C]")

# df is made here too

result = make_result(select, df)

print(result)

[data.py]

# where I want to deal with data things
# such as making a query to Pandas data frame

def make_result(select, df):
    result = df[df['choice']==select]['result'].values[0]
BatWannaBe
  • 4,330
  • 1
  • 14
  • 23