SoFunction
Updated on 2024-11-15

The Unseen Side of Python Functions

Usually we define a function and then the code related to the function starts executing when we call the function. However, many people don't realize that some code starts executing when we define a function. Today we will talk about this unknown side of functions.

Usually we define a function and then the code related to the function starts executing when we call the function. However, many people don't realize that some code starts executing when we define a function. Today we will talk about this unknown side of functions.

Let's look at a piece of code first:

def do_something(opt: print('Parameters opt'), arg=print('Parameter arg')) -> print('The return value of the function'): 
    print("do something runing") 
 
if __name__ == '__main__': 
    pass 

In the above code we define a function, but don't call it, so will it output information?

Yes, the statements in the parameter, whether it's the type hints section, the default assignment section, or the type hints for the return value, will be executed with the following results:

This is a rare practice myself. Replace the print function with something like opening a file, connecting to a database, or whatever, and it will all be executed as well.

Typically, though, the arguments are immutable types, and if you pass in a mutable type, it's possible that with each function call, the result will be altered, for example:

def do_something(opt: print("Parameter opt"), arg=[]) -> print("The return value of a function."): 
    print("do something runing") 
    print(f"{arg = }") 
    (0) 
 
if __name__ == "__main__": 
    do_something(opt=1) 
    do_something(opt=1) 

The results of the run are as follows:

As you can see, calling the do_something function twice sends a change in the value of arg, even though no arg parameter is passed in. If you don't pay attention to this, a bug may occur. In Pythcarm, we are warned that arg is a mutable object:

If you want to get the type hint, default value of the function, you can do this:

def do_something(opt: 1, arg=2) -> 3: 
    print("do something runing") 
    print(f"{arg = }") 
    (0) 
 
 
if __name__ == "__main__": 
    print(f"{do_something.__annotations__ = }") 
    print(f"{do_something.__defaults__ = }") 
 
#do_something.__annotations__ = {'opt': 1, 'return': 3} 
#do_something.__defaults__ = (2,) 

to this article on the Python function of the unknown side of the article is introduced to this, more related Python function content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!