Home > Net >  Calling a function or the whole file
Calling a function or the whole file

Time:05-27

Before I ask the question let us assume the following two python files as listed below. When calling file2.bar() in file1.py does it then ONLY call the function bar from file2.py or does it also call all the code that is outside the function as in this case being foo = 'Hi'?

file1.py

import file2

x = file2.bar()

file2.py

foo = 'Hi'

def bar():
    a = 10
    return a

CodePudding user response:

When you execute import file2, all of the code in file2 is executed (with the exception being code contained inside a if __name__ == '__main__' statement which does not apply in your case). This includes all variable/function/class definitions.

Calling file2.bar() will only call the bar() function - it does not re-execute your foo definition. However, the foo variable does still exist as it was defined when you called import file2. You can access foo using file2.foo.

There is more information on python modules in the documentation here.

CodePudding user response:

I think you need to be careful of your terminology. import file2 doesn't call anything; it executes the code in file2.py, and thereby creates a namespace file2. In particular, when the code is imported, and therefore run, the objects file2.foo and file2.bar are created^*. The former is equal to 'Hi' and the latter is the function you defined.

^*along with quite a few objects related to how python stores information, which you don't normally need to worry about

CodePudding user response:

The first time the Python import machinery has to import a file, the whole file is executed, then either a reference to the module (for import file2) or references to some symbols (for from file2 import bar) are added to the importing module.

If the module is later imported again, only the relevant symbols are locally added but the module body is not executed again.

So, for your direct question, foo = 'Hi' will be executed.

  • Related