Home > Enterprise >  Why does a line of code that is outside a function (when the function is called in another file) pri
Why does a line of code that is outside a function (when the function is called in another file) pri

Time:09-22

When I create a function in a file (let's call it demostration_1.py) and some other line of code outside the function, as shown below:

def adult(x):
    return x >= 18

print('hello world')

and then I call this function in another file (let's call it demostration_2.py)

from demostration_1 import adult

print(adult(18))

it prints out

hello world
True

So, Why does it print hello world if I'm only calling for the adult() function?

CodePudding user response:

just to expand on my comment above, but imagine that your module a contains the following code:

def adult(x):
    return x >= MIN_YEARS


MIN_YEARS = 18

This works perfectly fine, but only because the entire module is loaded when you call import a or from a import adult.

But if you didn't want a block of code to be run whenever a module was imported, you can hide that logic away within an if __name__=='__main__:' block at the end of the file, as @Tim Roberts also mentioned. So with the below approach, you won't see hello world printed whenever this module is imported by another one.

def adult(x):
    return x >= 18


if __name__ == '__main__':
    print('hello world')
  • Related