1

Hi I'm confused by importing functions form another .py file

My question is this

I made two .py files

First one named qq.py

def bb(x):
    x = aa(x)
    return x+3
def aa(x):
    return x+ 6

Second one named test.py

from qq import bb
print(bb(10))

*add comment : test.py worked

I thought that test.py wouldn't work.
Because function bb requires function aa and function aa didn't imported

Why this worked?

Thank you.

Jake
  • 65
  • 4
  • 2
    Code in the module runs in the module's namespace, not the importer's namespace, so it can refer to other code in the module. – Barmar Mar 30 '22 at 06:07

2 Answers2

2

This is similar to a question I posted a few days ago. Basically, when you import bb in test.py, it brings along a reference to the namespace of the module where bb was defined. So, in test.py, if you try:

from qq import bb
for x in bb.__globals__:
    print(x)

you'll get the output:

__name__
__doc__
__package__
__loader__
__spec__
__file__
__cached__
__builtins__
bb
aa

So, you can see that both bb and aa are recognized in test.py.

Carlo
  • 1,321
  • 12
  • 37
1

It will work because python just need the child function and it will call its dependency automatically