3

Assume we have two files "a.py" and "b.py"

a.py

from b import funcB

funcB()

b.py

varB = 123

def funcB():
    print(varB)

As you see in "a.py", I importing from "b" ONLY "funcB", after that I execute "funcB" in "a", but some how "funcB" CAN SEE "varB" defined in "b". But I have ONLY imported "funcB". I thought "from b import funcB" would ONLY import "funcB" and nothing else.

Why can "funcB" access "varB"? Is that is some kind of design decision?

Thanks

user2624744
  • 693
  • 8
  • 23
  • 7
    *"Is that is some kind of design decision?"* Yes. The whole module is really imported, but only the name you specify added to your current namespace. Otherwise, the functions you import would be unable to access e.g. helper functions and imports defined in their source script, which would be very unhelpful. – jonrsharpe Dec 19 '14 at 12:32
  • 1
    Related: [How does from ... import ... statement import global variables](http://stackoverflow.com/q/25283616) – Martijn Pieters Dec 19 '14 at 13:04
  • This is also useful: [from import vs import](http://stackoverflow.com/questions/9439480/from-import-vs-import) – Reut Sharabani Dec 19 '14 at 13:50

1 Answers1

0

when you import a module, it will not only give you access to what you have just imported. It will also execute the whole script.

This is why you can see in many script

if __name__ == '__main__':
    some code

otherwise, some code would be executed on import. So all the function of the module are declared, and all the 'out of function' code is executed. And this is logic, otherwise, a function could never use something which have not been given to it in parameter, not even an other function.

Borbag
  • 597
  • 4
  • 21