Import module - undefined global variable

479
4
06-04-2012 08:00 AM
DonBarker
Occasional Contributor
I thought I understood and fixed this problem:  A variable defined in a module remains undefined after I import the module.  Here is the simplified version.

The main script and the module are in the same folder/dir.

This is my module:  mysettings.py

def main():

    myvar = "This is imported."

if __name__ == '__main__':
    main()



This is my script:  irp.py:


import mysettings

def main():

    print myvar

if __name__ == '__main__':
    main()



Interpreter error:

NameError: global name 'myvar' is not defined

Can you tell me why?

Thanks,
Tags (2)
0 Kudos
4 Replies
MathewCoyle
Frequent Contributor
You need to do something like this in your irp.py

mysettings.main()


When you import a module it isn't executed as the __main__ so it needs to be called by function if you have it setup that way.
0 Kudos
DonBarker
Occasional Contributor
Matthew,

Thanks for taking time to reply.

I'm a Python novice so don't understand how/where to use this in my script.  Can you explain?
0 Kudos
MathewCoyle
Frequent Contributor
Your mysettings.py should be something along these lines, depending on what it does.

def main():

    myvar = "This is imported."
    return myvar

if __name__ == '__main__':
    main()


Your irp.py should be something like this.

import mysettings

def main():

    print mysettings.main()

if __name__ == '__main__':
    main()
0 Kudos
DonBarker
Occasional Contributor
Got it now.  Thanks again for taking time to reply and explain.
0 Kudos