1

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
FotisK
  • 1,055
  • 2
  • 13
  • 28
  • Mind the namespaces, I have explained more about this here: http://stackoverflow.com/questions/22408302/why-cant-pythons-import-work-like-cs-include/22408375#22408375 – bosnjak Apr 10 '14 at 14:17
  • "I read that if something is imported that it doesn't need to imported again, does that mean i can import everything in the main.py and it will be available also to the other project files??" No, you will need to import either the module or the functions you want to use in every file which requires them. The module itself is _read_ once when first imported and stored in `sys.modules`, every other import during the lifetime of the program will refer to that stored module rather than re-reading it from disk. – Matthew Trevor Apr 10 '14 at 15:12
  • Thanks to you all for your time and answers! – FotisK Apr 10 '14 at 15:49

2 Answers2

2

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.

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
1

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

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304