1.11M Members

Calling function in main module from import

 
0
 

How do you get an imported function to find a function in the main program? This runs fine if I put the generate_random function in with the main, but if it is in an imported function it can't find the printa function in the main. It comes up with the error "NameError: global name 'printa' is not defined". How do I define it?

#-------------------------------------------------------------------------------
# Name:        main_module

#------------------------------------------------------------------------------

from submodule import *
num_values = ["zero","one","two","three","four","five","six","seven"]

def printa(valuea):
    print (num_values[valuea])

generate_random()





#-------------------------------------------------------------------------------
# Name:        submodule.py

    printa(a)
#-------------------------------------------------------------------------------
from random import randint
def generate_random():
    a = randint(0,4)
 
0
 

The best solution to avoid circular imports. If A imports B, then B should not import A, or import from A (although python is very permissive and will tolerate almost everything). Here, main imports submodule and both use printa(). You can write printa() and num_values in a third module, and import thirdmod in both main and submodule.

 
0
 

Yes, I think I will go back to putting my entire program in the main module. It is about 500 lines long that way, (I'm web scraping from several sites for one report). The functions are so interrelated that it keeps jumping back and forth.
Thanks for the reply.

 
1
 

There is no problem in jumping back and forth if you do it through class instances, for example in module A

# mod A

from B import foo

class Bar(object):
    def baz(self):
        print("qux")

x = Bar()
foo(x) # call function foo from module B

and in module B

# mod B

def foo(bar):
    bar.baz() # call method .baz() defined in module A

Notice that module B uses module A features without importing anything from A.

 
0
 

This looks like the way I want to go. It will make my head hurt trying to get it straight, but would make my imported module much more reuseable.
Thanks again

Question Answered as of 1 Year Ago by Gribouillis
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article