Can I print a variable from one function in another .py file

Viewed 35

for example lets say I have a file called "utils.py". I have a function that passes user input through a series of "if" statements. Every time X conditions are met the original variable is altered and saved as a new variable then passed down to the next if statement. I want to access the final altered variable from a source file called "main.py". I would prefer if there was a method with no temp file. I have searched for an answer online for a while but found nothing quite as specific as what i am looking for.

to clarify i have a file called "utils"

if x == "y":
    s = x.replace("blah", "blah")
    print s
global I1_b
I1_b = s

then in another file called "main" i would like to call I1_b

if this == "that":
    print(I1_b)
4 Answers

You can import the utils.py file in the main.py file, then use I1_b there.

It would like this:

# In main.py
import utils
if this == "that":
    print(utils.I1_b)

The logic in the utile.py folder would be better inside a function and import that function in the main.py file. The code in utils.py will now always be executed once you import anything from it.

from utils import function_x

print(function_x())

global is not the correct tool here. That is used inside a module (file) to define a global scope (https://www.programiz.com/python-programming/global-keyword), and read/edit variables accordingly.

The best solution is to import the I1_b variable from the utils module, like: from utils import I1_b, and use it as you intended

def get_value(x):
    if x == "y":
        s = x.replace("blah", "nah")
        print(f"X is {x}")
        return s

your_answer = get_value(input("Input y: "))
print(your_answer)

To access it from another file, see @barmar comment import utils

Related