Basic Question

Antaeus Feldspar feldspar at ix.netcom.com
Fri Feb 15 15:06:15 EST 2002


Karthikesh Raju wrote:
> 
> Hi,
> 
> Just started, so my question might be stupid. i tried this:
> 
> import random
> 
> def randomList(n):
>     s = [0] * n
>     for i in range(n):
>         s[i] = random.random()
>     return s
> 
> in a file called randomList.py. Started python, imported randomList
> (>> import randomList) and then called this function (>>
> randomList(5)), got this un-understandable error:
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: object of type 'module' is not callable
> 
> But when i when type the function at the python command prompt, it
> works. Couldnt figure out why..
> 
> Thankx in advance,
> 
> Best wishes
> karthik

When you put a function named "functionName()" in a file called
"moduleName.py", the name of that function in another namespace (such as
that of the interpreter) is not "functionName()" but
"moduleName.functionName()".  (There's an exception, if you use the
"from <module> import <names>" statement, but I don't recommend that
until you've got the basics down.)  You can see this if you look at the
code inside your function:  to get a random number, you called
"random.random()" -- i.e., the "random()" function inside the "random"
module.

Your module name and your function name happen to be identical.  When
you typed in your function name, unqualified by a module name, the
interpreter looked for anything in its namespace matching "randomList". 
It found an object that matched that name -- but it wasn't the function
*in* the module, it was the module itself, which had the same name.

When you typed the function at the interpreter prompt, *then* you
established a function with the name randomList in the interpreter's
namespace.  And then, of course, it worked.

If you want to call the function in the module, you'd have to use
"randomList.randomList(n)".

If you want to see what's in your interpreter's namespace at a given
time, you can use the "dir(<name>)" command.  Try it before you import a
module, and after, and try using a name returned by one call to "dir()"
as an argument to the function.  It may help you understand better how
Python namespaces work.

	-jc



More information about the Python-list mailing list