Search code examples
pythonpseudocodeconventions

Variables dependent on a variable not assigned (Good Practices)


Basically put:

def function1():
    y = x + 2
    return y

def function2():
    x = 2
    return function1()

function2()

When you have multiple functions that depend on other functions and you get assignments after already writing a variable dependent on another one like the y needing the x before it was assigned on the code above.

I know this won't end up giving any errors since func1 is called by func2 so should I just not care and stop obsessing about it? I feel like this is kinda messy and might get in the way of testing and I keep getting the warnings in the editor which lead me to believe that this is not a good way to go about things.

What would be the best practice in cases like this, or how would you prefer to solve this, I know I could explicitly pass the variable to the function to solve this, but I was wondering if there was a better and more readable way of going through this.

Thanks. :D


Solution

  • Just to reinforce what the comments have said, here is a proper way to write that. No external dependencies:

    def function1(x):
        y = x + 2
        return y
    
    def function2():
        x = 2
        return function1(x)
    
    print(function2())