0

I've distilled down what I'm trying to do to the simplest form. I have a one module (prog1.py) that runs fine. A function in prog1.py accesses a variable (yy) OK without an error.

#prog1.py 
def func():
    print (yy)
    return()

def main(yy):
    print(yy)
    func()
    return()

#-----------------------------------------------
if __name__ == '__main__':     
    yy = 200
    main(yy)

When I import that module into another module (prog2.py) the same function cannot access the variable (yy).

#prog2.py
import prog1
yy = 200
prog1.main(yy)

I get:

name 'yy' is not defined in line 3 in func.

What is the "correct" (python) way to do this?

RustyC
  • 59
  • 3

1 Answers1

0

Issue is in func:

def func():
    print (yy)
    return()

Line print (yy) tries to access yy, but if __name__ == '__main__': will not be true for that module (__name__ will be prog1 not __main__), hence it will not go inside if:

if __name__ == '__main__':     
    yy = 200
    main(yy)

Hence yy will not be defined.

Read more about if __name__ == '__main__': in this question.


According to what you have mentioned in the comments:

#prog1.py

yy = 'prog1 yy'


def func():
    print(yy)


def main(yy):
    print(yy)
    func()


if __name__ == '__main__':
    yy = 200
    main(yy)
# prog2.py

import prog1


yy = 200
prog1.main(yy)

Run:

python prog2.py

Output:

200
prog1 yy
Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
  • I understand, but `yy` is defined in the `main(yy)` routine as the print works. The problem only occurs when `func` tries to use `yy`. – RustyC Oct 10 '19 at 08:02
  • We have passed `yy` to the `main` function, hence it can access it (scope of `yy` is limited to `main`, `func` doesn't know about it). You have to explicitly pass it as a parameter to `func`, so that it can access it (similar to what you did to `main`). – Dipen Dadhaniya Oct 10 '19 at 08:10
  • OK thanks Dipen, but I was trying to do it without resorting to passing `yy` as a parameter. Is `global` the way to go? Although I gather some people say not to use it. – RustyC Oct 10 '19 at 10:51
  • Yes, using a global variable it is possible, but whenever possible, we should try to avoid global variables. – Dipen Dadhaniya Oct 10 '19 at 10:55
  • I did try using global but still got the error. Can you indicate how to use global in the situation I described? – RustyC Oct 10 '19 at 12:17
  • Updated the answer! Please check! – Dipen Dadhaniya Oct 10 '19 at 12:30