pythonpython-3.xfunction-declarationinterpretation

How Python deals with redeclared function


I have occurrences of accidentally redeclared functions in a python codebase. The occurrences are simple function definitions, no functools.singledispatch involved. I want to fix that. However, I do not know which of the functions python actually uses. I want to keep only that function.

Please understand, that I ask this question to understand what happens behind the scene and how to solve the issue properly. Of course, I know that redeclaring functions in python is bad coding practice. I also know that a linter can hint you on that. But if the problem is there and I want to solve that, I must understand and find out all of which occurrences should be deleted.

I made a small test and it seems that python actually uses the last definition:

def func1(a: int):
    print("Num", a)


def func1(a: int):
    print("A number: ", a)


func1(100)

->

/home/user/PycharmProjects/project/.venv/bin/python /home/user/.config/JetBrains/PyCharm2023.1/scratches/redeclared_func.py 
A number:  100

I just wanted to ask, to be sure that this interpretation is correct. In that case I would keep none but the last occurrence, of course. There may be a difference between, e.g. Python versions, Python interpreters etc. What happens, if a module with redeclared functions is imported and then the function is redeclared again?


Solution

  • The definition that holds is the last that was met in the flow of execution, just as if you were assigning a variable.

    E.g.

    def F():
        print("First")
    F()
    
    if True:
        def F():
            print("Second")
        F()
    else:
        def F():
            print("Third")
        F()
    
    F()
    

    says

    First
    Second
    Second