Mystery of module bindings!

Discussion in 'Python' started by Peter Rowat, Apr 29, 2013.

  1. Peter Rowat

    Peter Rowat Guest

    This must be a trivial question:

    I have "import numpy as np" in the python startup file.

    A file called mod1.py contains "def myfn..."
    and inside myfn there is a call to, say, "np.convolve".

    Interactively:
    ..... (numpy imported as np)
    Error: global name "np" is not known.
    =======
    Why is "np" not known to functions in an imported module ?
    =======

    I can fix this by including "import numpy as np" in any module that uses numpy
    functions -- but then what is the point of having a startup file?

    -- PeterR
     
    Peter Rowat, Apr 29, 2013
    #1
    1. Advertisements

  2. That only runs interactively. It does not run when you execute a script.

    Let's suppose it was. What would that mean?

    Look inside mod1, where there might be a function spam(), and also
    another function eggs(). spam() calls eggs(), it sees the eggs function
    in the same module, and all is well with the world.

    Then you add to the startup file:

    def eggs():
    return "Something unexpected"


    and all of a sudden mod1.spam() breaks, because it now sees *your* eggs()
    instead of its eggs. This would be a bad, bad thing.

    This is why modules are their own namespace, and the interactive
    interpreter is its own, independent, namespace. What happens in the
    interactive interpreter stays in the interactive interpreter, without
    stomping all over every other module.

    The point of the startup file is to add things to the interactive
    interpreter's module, not to inject things into every module in sight.
     
    Steven D'Aprano, Apr 29, 2013
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.