Home > Enterprise >  How can I access variable, which was assigned in another python script?
How can I access variable, which was assigned in another python script?

Time:10-25

I have two scripts, let's say "reading" and "calculation". Script "reading" has inside of it several functions, and reads data from csv files and creates pandas dataframes. Let's say it defines variable "dataframe_1". Script "calculation" makes some calculation with dataframes, which were defined in script "reading".

I want to run script "calculation" after I ran script "reading", and use its results somehow. How can I access that variable (dataframe_1) inside script "calculation", after it was defined in script "reading"?

I assume during execution of script "reading", dataframe_1 is stored in operating memory, how can I access it?

If I do it like that, it reads dataframe_1 again, instead of just accessing the result of reading, which are stored in memory?

from reading import dataframe_1

CodePudding user response:

The results from applying the functions from the calculation.py script would have to be stored in a variable again which you would want to import.

CodePudding user response:

There are multiple ways to import variable. One way is this.

import filename

new_var1= filename.variablename

CodePudding user response:

First write a function or a method that returns a dataframe in reading.py e.g.

def foo(arguments):
   # create dataframe
   # return dataframe

Then, import foo in calculation.py to generate dataframe:

from reading import foo
dataframe = foo(arguments)

# do calculations on dataframe

Variable names that we create are references to the objects stored in memory in Python. So, calculation.py must know where the dataset created by reading.py is stored in memory. Please check Other languages have "variables", Python has "names".

Please also check how importing works in Python.

  • Related