Python import and scope

Suppose 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 can see in "a.py", I import from "b" ONLY "funcB", after that I execute "funcB" in "a", but some like "funcB" MAY SEE "varB" defined in " b ". But I ONLY imported "FuncB". I thought that "from b import funcB" would ONLY import "funcB" and nothing else.

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

thank

+3


source to share


1 answer


when you import a module, it will not only give you access to what you just imported. It will execute the entire script as well.

This is why you can see in many script



if __name__ == '__main__':
    some code

      

otherwise it some code

will be executed on import. Thus, the entire function of the module is declared, and all code is executed "outside the function". And this is logic, otherwise the function will never be able to use something that was not given to it in a parameter, not even some other function.

0


source







All Articles