Global name is not defined when running script with closures with execfile

155 Views Asked by At

I am trying to run script2 from script1 with execfile and script2 contains closures:

script1.py

MyVar1 = 'value1'


def fun1():
    print(MyVar1)


def fun2():
    execfile('script2.py')

fun1()
fun2()

script2.py

MyVar2 = 'value2'


def fun1():
    print(MyVar2)


fun1()

An error occurs

  File "...script1.py", line 12, in <module>
    fun2()
  File "...script1.py", line 9, in fun2
    execfile('script2.py')
  File "script2.py", line 8, in <module>
    fun1()
  File "script2.py", line 5, in fun1
    print(MyVar2)
NameError: global name 'MyVar2' is not defined

How to fix script1 still using execfile?

UPDATE

If it is impossible with execfile then how to do otherwise?

1

There are 1 best solutions below

4
Paandittya On
MyVar2 = 'value2'

def fun1():
    global MyVar2
    print(MyVar2)

fun1()

The fix needs to be done in script 2 actually.