[Tutor] OK real basic problem ...

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Mar 11 10:23:38 EST 2004


> I've created a file called pycode ...
>
> #!/usr/bin/env python
> print "hi my module is loaded !!!\n"
>
> def addit(a,b):
>         print a+b
>
> good so far, chmod a+x pycode

Actually to import the file you don;t need to make it executable,
merely readable... However if you ever want to run it standalone
you will need +x. Just a wee point.

> >>> import pycode
> >>> reload(pycode)

YOu shouldn't need the reload!

> hi my module is loaded !!!

And this should have printed on the initial import too.
> >>> addit(1,2)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'addit' is not defined

An import(or reload) imports the names that you give it
- in this case "pycode". It does NOT import the names inside pycode.
(You can do that with "from pycode import *" but as you will see
thats usually a bad idea.)

So you have imported the name pycode which refers to your file(or
module).

To access the contents of your module prefix the function with
the module name:

pycode.addit(1,2)

>  From my message "hi my module has loaded ... I thought addit()
would
> work ..

When you import a module it executes all the code in that module.
Your print statement is simply being executed by the import. Your
function definition is likewise being exactuted and a function
object created. But you can't directly see that object because
its inside pycode.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list