Question

I am writing an IPythonNotebook and to make my code less clustered, I am defining some functions not in the main notebook. I outplace them in external .py-files which I import.

Why doesn't test() know of u()?

In the myModule.py-file

def test():
    number = u()+u()
    return number

And my main file (in the notebook)

from myModul import test

def u():
    bla = 1
    return bla


test()

My test()-function is imported well, but does not know u:

NameError: global name 'u' is not defined

Was it helpful?

Solution

You cannot do this; globals are only ever looked up in the module the function is defined in.

You'd instead give your function a parameter that accepts u as an argument:

def test(u):
    number = u()+u()
    return number

and in the main file:

def u():
    bla = 1
    return bla

test(u)

If Python worked the way you expected it to, you'd create many hard-to-trace problems, which namespaces (like modules) were meant to solve in the first place.

OTHER TIPS

python does not have the idea of global functions - functions exist in modules. Even variables are only global inside a module, and can't be seen by any other module unless they are imported.

so if you want your test function to be able to see your function "U" - you either need to : 1) import your mainmodule into myModul - not a great idea as you end up with circular dependencies.

2) Follow Martijn Pieters excellent idea of passing function u into your test function

3) Think about the organisation of your code - if your "test" function really depends on calling "u" then should they be defined in the different modules ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top