user1654183
user1654183

Reputation: 4605

IPython interactive running using imported module

I have a module as follows:

module1.py

Class bla():
  code here

def main():

  g1=bla()

if __name__ == '__main__':
  main()

When I do ipython module1.py or go into IPython and import module1 the code runs as expected. However, when I then type something like print g1 it says that g1 is not defined, even though I defined g1 in the main program. It seems that the code runs the main program and then "exits" it somehow and just leaves me with the ipython prompt. I want to use the variables that I defined in the main function...

How do I do this?

Upvotes: 1

Views: 115

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

You would have to mark g1 as a global:

def main():
    global g1
    g1 = bla()

Normally, any name defined in a function is local to the function only. You'd still have to import the name from the module, or refer to it as an attribute of the module:

import module1

print module1.g1

Upvotes: 3

Related Questions