0

My app.py is

print("Start")

def increment(x):
    print("Increment")
    return x + 1

print("Finish")

When I run it in terminal

user$ python
Python 3.7.2 (default, May 23 2020, 08:27:09) 
[Clang 10.0.0 (clang-1000.10.44.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import increment
Start
Finish
>>> increment(5)
Increment
6
>>> 

Why is Start and Finish printed even though I'm only importing function 'increment'? Thanks!

user8865059
  • 71
  • 2
  • 13
  • 2
    You can't `import` anything less than a full module; a single function from the module can arbitrarily access other things from the same module, so no attempt at limiting what gets executed is safe. – jasonharper Oct 14 '20 at 17:53
  • 4
    Does this answer your question? [Import a python module without running it](https://stackoverflow.com/questions/31031503/import-a-python-module-without-running-it) – Random Davis Oct 14 '20 at 17:54

1 Answers1

0

Python imports always import the entire module. from x import y is just a little syntactic sugar for something roughly equivalent to:

import x  # Import whole module
y = x.y   # Put the requested names in global scope
del x     # Remove direct access to module itself

With the minor difference that x is never technically in scope at all so no deletion is involved (so stuff like from x import x works).

It doesn't change the cost of the import, or limit what gets imported, it just limits which names you have access to and removes the need to qualify the names (because they're dumped into the global namespace directly, not accessed as attributes of the module).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271