importing module versus using function?
Robert Kern
robert.kern at gmail.com
Tue Jan 31 10:53:03 EST 2012
On 1/31/12 3:08 PM, gujax wrote:
> Hi,
> I am confused on this quite bad!!
> If I have this typed in interactive python:
>
>>> import numpy
>
>>> def dummy():
> y=numpy.arange(1,2,0.1)
> return y
>
> and then
>>> s = dummy()
>>> s
>>> array[1. , 1.1, 1.2........]
>
> it works.
>
> But if I have a module called example.py, whose code is
>
> def dummy():
> y=numpy.arange(1,2,0.1)
> return y
>
> and now if I do the following:
>
>>> import numpy
>> >from example import *
>>> s=dummy()
>
> The above sequence does not work. It gives an error saying global
> variable numpy not defined.
>
> I understand that when I import a module it gets imported after
> getting compiled and therefore, the module should
> have a statement "import numpy" at its start.
>
> But what if I just want to use the function 'dummy'?
You need to import numpy in dummy.py. When a function needs to look up a name,
it goes to the module's namespace in which the function is defined, not one of
the many namespaces where the function is called from.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list