ive been trying my hand on using modules to make my codes cleaner.
i started off with a simple case.

i created a module, usermodule.py, which i will pass to a main program

openme.jpg - 640x480

#this is usermodule.py
import Image

#image = Image.open ('openme.jpg')       
#imload = image.load()                   

def usermodule(x,y):
    return imload[xstart,ystart]

i then created a main program and pass usermodule.py to it:

#this is the mainprogram
import Image , usermodule

image = Image.open ('openme.jpg')
imload = image.load()

print usermodule.usermodule(1,1)

when i run the main program however, i get this error:

NameError: global name 'imload' is not defined

any light you can shed as to why this is happening is much appreciated. thanks

6 Years
Discussion Span
Last Post by iwanttolearnc

Each module has its own 'namespace', that is to say its own dictionary of known variable names. In your example, the (global) names defined in the module 'usermodule' are 'Image' and 'usermodule. The names defined in the main program are 'image', 'usermodule' and 'imload'.

It means that the function usermodule() doesn't know that there is a variable imload, since it can only see the namespace of the usermodule module. It's an error to use imload in the function's body. Also, another error is that xstart and ystart are not defined anywhere.

The solution is to pass the value of imload to the function through an argument. You can write

# in usermodule.py
def usermodule(imload, x, y):
    return imload[x,y] # imload, x, y are known names in this scope, since they are parameters

# in main program
print usermodule.usermodule(imload, 1,1)

Edited by Gribouillis: n/a


thank you for replying. is there a way to share the imload variable to usermodule and still achieve the necessary results? what im going for here is that the main program calls the imload and then usermodule uses that imload.

Also, another error is that xstart and ystart are not defined anywhere.

my bad there that should have been

return imload[xstart,ystart]
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.