[Tutor] Modules and variable usage in functions from other files

Alan Gauld alan.gauld at btinternet.com
Thu Dec 24 05:28:43 EST 2015


On 24/12/15 01:45, Richard Bekenstein wrote:

>        from scipy.constants import m_p,G,k
>        import numpy as np
>        from math import cos, pi, floor
...
>        from bol_runge_kutta_evl_nonadaptive import runge_kutta_evl 

>    When I run this main.py, I get an error message from the imported
>    'runge_kutta_evl' function that numpy is not defined. Why is it that even
>    though I have it defined in my script it does not recognize it in my
>    function called to the script? 

The function is in the other module. You only imported the names
into your main module, that does not make them visible in the
other modules.

Making the function *name* visible in main (by importing it) does
not make the function *object* to which the name refers part of
main. The function object remains in the original module. So
you need to import all of the names the function uses into
its module too.(**)

> It turns out that even if I then state
>    'import numpy as np' in my 'runge_kutta_evl' function, I then another
>    error that 'r_range' is not defined. But aren't 'r_range' and 'np'
>    supposed to be accesible to all called functions in the main .py?

They are visible in main but they are not visible in the
other modules that main imports. Importing only makes things
visible to the module doing the importing. Python has no
concept of a "main" module as a kind of global namespace,
it treats your main.py just like any other module. It only
exposes the names you import to main.py Every module must
import the names it needs and in that way becomes an
independent, and therefore reusable, piece of code.

BTW In future, please include the full error message in any
posts. Although in this case we could just about guess
what it looked like, its better to see a cut n' paste
version in case there are subtle clues hidden in the message.

(**)The fact you are getting these kinds of errors suggests
you are not testing the individual modules in isolation
from your main program. It's a good habit to (as a minimum!)
import any modules you write into the interpreter and exercise
the functions manually to be sure they work. That would have
revealed that the modules did not have access to all the
names they needed to work. Even better would be to start
using some of the automated test tools such as unittest
or doctest to ensure your modules work consistently after
each change.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list