Importing value of a variable from one file to another without executing the function in python

I have a script test.py which contains two functions sum() summing up two values and meth() calling sum() and storing result in a variable c. My intention is to run meth() and get the value stored in variable c first and then want to use this value in another script demo.py without executing sum() again. is it possible?

test.py

def sum(a,b):
    print("inside sum function")
    return a+b
    
def meth():
    c = sum(7,5)
    return c

The solution I tried:

I am getting value of variable c by calling meth() in demo.py But it is executing sum() function also.

demo.py

import test.py as tes
val = tes.meth()

output:

=> Inside sum function
=> 12

I want to run test.py first and store the value in variable c and use it in demo.py without executing sum() function again.

Upvotes: 0

Views: 142

Answers (2)

rioV8
rioV8

Reputation: 28663

Don't use a file called test.py because test is a buildin module.

In mytest.py call sum() and store it in a hidden module variable. Use this variable when you call meth()

mytest.py

def sum(a,b):
    print("inside sum function")
    return a+b

_singleCallOfSumInMeth = sum(7,5)

def meth():
    return _singleCallOfSumInMeth

demo.py

import mytest
print('After import, before calling meth()')
val = mytest.meth()
val = mytest.meth()
val = mytest.meth()
val = mytest.meth()
print(f'val={val}')

Output

inside sum function
After import, before calling meth()

inside sum function is printed because of the import mytest. And it is printed only once and we call meth() multiple times. So sum() is only called once while calling meth()

Upvotes: 0

Michael
Michael

Reputation: 2414

Every time that you call meth(), it will invoke sum(). When that process exits, the memory is freed and the results of the sum are lost until you run the function again.

If you want to store that result somewhere then you could write it to a file, e.g. as text or some binary format or even using pickle, and then load it later in some other process. You'd have to modify meth() to store the result of sum(), and then have it check for that file the next time that it's invoked. This is basically caching, and there are all kinds of modules that will let you do advanced caching if you want to go beyond storing the sum of 2 numbers in a file.

Upvotes: 1

Related Questions