Importing modules (beginner level)

Hello everyone, I’m a begginer and I’ve got a question and I hope it will be answered, and you won’t block my account for asking banal questions like Stackoverflow.

Right now I’m learning the modules.
Let’s imagine that we’ve got 2 files and “ (<- in this file we defined some functions)

Let’s import the functions of “” to (they are in the same folder)

So, we have two options to do that. Write:

  1. Import functions
  2. from functions import function_x, function_y

In “” in the end of the page, outside of definitions let’s write print(“something”)

It’s gonna be printed out for Import functions , which is normal as I think, because we import the entire file.

However, it’s gonna be printed out for from functions import function_x, function_y as well.
And this I can’t understand, because there we specified what function we want to import and from what file. Nothing else.
So, the print(“something”) is outside the definitions we asked to import, how is it getting imported? If it’s gonna be printed out, anyways, so why did we specify each function one by one carefully?

Thank you in advance!

When you import, the whole file is read and processed. Then depending on whether you did import functions or from functions import function_x the desired items are collected from that file and added to your current namespace. All of the contents of the imported file are required to be processed, regardless of the names you select for local use.


x = 1
def function_x(y):
    return y+x
def function_y(z):
    return function_x(z)

Even if we import just function_y, we still require x and function_x for it to work properly.