0

The get_square_root() function relies on the math module. To call the get_square_root() function in analysis.py, I don't need to import the math module, why is that?


# calculator.py

import math

def get_square_root(a):
    return math.sqrt(a)
#analysis.py

import calculator

calculator.get_square_root(5)

Something I know about import in python (Correct me if I understood sth. wrong). When import calculator, the Python interpreter reads the whole calculator.py module, but the objects in the module not to be accessed by <ModuleName>.<ObjectName>. This is how I call the get_square_root() in analysis.py. But how the get_square_root() access math since there no math in analysis.py ?

baicai
  • 45
  • 5

1 Answers1

1

When you run calculator in any way, math is bound in its module scope, making it accessible to get_square_root.

When you run import calculator in analysis, math is still in the module scope for get_square_root, plus calculator is bound in the scope of analysis so you can access it as calculator.math.

When you run from calculator import get_square_root in analysis, math is still in the module scope for get_square_root, but you cannot access it from analysis since calculator is not bound.

wjandrea
  • 28,235
  • 9
  • 60
  • 81