importing module versus using function?

G

gujax

Hi,
I am confused on this quite bad!!
If I have this typed in interactive python:
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:

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'?

I tried the following:
from example import dummy
and then try to use the function, it still gives me 'global name numpy
not defined'!

Why is that happening?
Any pointers please.
Thanks
 
R

Robert Kern

Hi,
I am confused on this quite bad!!
If I have this typed in interactive python:
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:

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,998
Latest member
MarissaEub

Latest Threads

Top