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.

1
  • 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. Commented Mar 30, 2022 at 6:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.