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)

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.

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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.