How to assign a variable within a function to be referenced in later in code?

Viewed 73

I am having some issue calling a function from another file to set a variable in my current file, looking for help.

This works:

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Correctly prints 'Python is fantastic'

This doesn't work:

File1.py

def myfunc():
  global x
  x = "fantastic"

file2.py

from up2levels.up1level.file1 import * 

myfunc()

print("Python is " + x)

result: 'x is not defined'. I want this result to be 'Python is Fantastic'

What am I missing here? Thanks for the help!

EDIT: I've tried some of the answers and still run into issues, they work in the very dumbed down example but, but I cant get it to work with my code. Here's what I'm trying to do: iterating over a data frame looking for certain parameters to show up (for loop). Once parameters are met, pass line of data frame into function (File1.py) to return 5-6 different variables and record them in File2.py.

2 Answers

File1.py

def myfunc():
    x = "fantastic"
    return x

File2.py

import File1 

print("Python is " + File1.myfunc())
x = 'fantastic'
in a function sets the variable locally.

use globals() to set variables globally.

def myfunc():
    globals()['x'] = 'fantastic'

myfunc()

print("Python is " + x)

I hope it'll useful for you.

Related