简体   繁体   中英

python: Accessing variable in functions in different modules

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM