That is just how imports work.
def my_function():
print("Hello")
What is the above snippet of code? It is a function definition for sure, but function definitions in Python are statements, and they must be executed in order to define the function. So when you import the above module, it executes the def
, which creates a new function and assigns it to my_function
. It's basically the same as:
my_function = ...definition..
So when you import a module, you always execute its contents. Otherwise you wouldn't be able to use any functions (or classes) in that module.
There are other ways to define functions in Python for sure.
def create_my_function(x):
def local_function():
print(x)
global my_function
my_function = local_function
create_my_function("Hello")
This is broadly equivalent to the original definition of my_function()
.
Since you can put any statements in a Python module, Python has no way of knowing which statements must be executed in order to define the symbols you are interested in. So it must execute all the statements.