1

I get a NameError during import of a function from a module concerning a function which is not even imported itself. Minimal example is:

test.py:

from test2 import test2_b

test2_b(arg=None)

test2.py:

def test2_a(arg=a):
    print('HI_a')
def test2_b(arg=b):
    print('HI_b')

Output of python test.py:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from test2 import test2_b
  File "/home/test2.py", line 2, in <module>
    def test2_a(arg=a):
NameError: name 'a' is not defined

Why is the NameError referring to the function test2_a (instead of test2_b, for which indeed the error should be raised) if test2_a is not even imported?

bproxauf
  • 1,076
  • 12
  • 23

2 Answers2

0

Because when you try to import from module test2, functions test2_a and test2_b are compiled, and simply the parameter a is not defined previously. Try to define it with any value, for example:

a="foo"
b="bar"
def test2_a(arg=a):
    print('HI_a')
def test2_b(arg=b):
    print('HI_b')

(same for b after!)
This should work. But then you'll encounter another problem:there is no function test_b to import ! Instead, in test.py: from test2 import test2_b . And then it should be OK.

matleg
  • 618
  • 4
  • 11
0

Python interpreter has to read and parse all of test2 file, to be able at least to know which functions are defined in this file, and find the one that you want to import.

It is not executing test_2_a function during the import, but it has to define it, and for that he has to know which is this a that you use as a default value (default values are set during the function definition and not during the function execution)

Gelineau
  • 2,031
  • 4
  • 20
  • 30
  • Hmm. I do not fully understand why the interpreter needs to know about any other functions that are completely independent of the one concerned (which are neither called by the imported function nor used in the main script). I'd understand that it complains for `import test2` since this imports the entire namespace, but for a single function I do not see the rationale. Even if it needs to know the names of functions, this would not necessarily imply it also needs to know the function signature. – bproxauf Jul 12 '23 at 13:16
  • 1
    We could imagine that it would be possible to make a limited parsing as you say, but this is not the way it works. Like another answer said, it runs all the module, which means it defines all the functions declared in the module, and possibly runs all the code of the module which is not contained in functions nor guarded by a `if __name__ == "__main__"` – Gelineau Jul 12 '23 at 13:24