Question

i have following problem. In my project i have the below files:

main.py:

import general_functions
...

def main(argv):
    make()                         # line 98
    bake()

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))   # line 120

general_functions.py:

def make(what):...

def bake(how):...

tcs_main.py:

import general_functions
...

class baking(object):
    def __init__(self, ...):
        muffin = 'chocolate muffin'
        make(muffin)
        bake(200)

When i run this ./main.py

i get:

Traceback (most recent call last):
  File "./main.py", line xxx, in <module>
    sys.exit(main(sys.argv[1:]))
  File "./main.py", line 98, in main
    make(muffin)
NameError: global name 'make' is not defined

The thing is that in general_functions.py i would like to have general functions that can be used in the main.py but also in tcs_main.py.

What am i doing wrong here?

How are the imports imported in python? I read that if something is imported that it doesn't need to imported again (in python), does that mean i can import everything in the main.py and it will be available also to the other project files??

Thanks in adv.

Was it helpful?

Solution

You're importing the general_functions module, but at that point, main.py doesn't know about its contents (or better said, doesn't load its contents into the main module). You could do:

from general_functions import make, bake

or the (in my opinion, better practice):

import general_functions
...

class baking(object):
    def __init__(self, ...):
        muffin = 'chocolate muffin'
        general_functions.make(muffin)
        general_functions.bake(200)

You can check this great thread: How does Python importing exactly work? about how import works in Python, and this other one: Local import statements in Python about import scopes.

OTHER TIPS

You imported only the module, not its contents. That's fine, but you must refer to make() as general_functions.make() in your mainmodule.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top