Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python define function inside if block or vice versa

Tags:

python

I have a function I want to take different form depending on the mode. Should I enclose the definition within the if statement or should I put the if inside the definition?

# Case 1
if mode == 1:
    def f(x):
        return x + 5
else:
    def f(x):
        return x - 5

# Case 2
def f(x):
    if mode == 1:
        return x + 5
    else:
        return x - 5

I have done both in the past and my static code analysis tools don't seem to complain. So I was wondering whether there is a Pythonic recommendation?

EDIT: From the comments so far, both cases seem acceptable. It depends on the use case. If mode is intended to be constant, Case 1 is preferred. If not, then Case 2.

EDIT2: This question actually arose as I was writing a function. It takes in mode as an input and depending on the mode perform similar operations except it uses a different subfunction defined solely within the function for those operations. As the subfunction stays constant during the running of the function, Case 1 would seem to be more appropriate.

EDIT3: Correction: In the past, I believed it was PyLint that was not comfortable with Case 1. These days, I use PyCharm and that doesn't seem to flag any issues with Case 1.

like image 777
Spinor8 Avatar asked Jul 14 '17 18:07

Spinor8


2 Answers

Depends on what you want to use it for. They can both be used in useful ways. Compare the two examples:

1.

    Mode = 1
    Number = 0
    def f(x):
        global Mode
        if Mode == 1:
            Mode = 0
            return x + 5
        else:
            Mode = 1
            return x - 5

    for i in range(0,5):
        Number += f(i)

Versus:

2.

    Mode = 1
    Number = 0
    if Mode == 1:
        def f(x):
            return x + 5
    else:
        def f(x):
            return x - 5
    for i in range(0,5):
        number += f(i)

The first of these examples is best when you want to switch between modes while the code is running. The second one is best for if you just want one or the other. The first function will always give you the answer 15, because the mode changes while it is running. However, the second function will give you outputs of 35 or -15 depending on what you set the mode to in the first place.

like image 125
Zard Avatar answered Oct 07 '22 00:10

Zard


Your function behaviour shouldn't depend on external values, so I would recommend to use the first example:

# Case 1
if mode == 1:
    def f(x):
        return x + 5
else:
    def f(x):
        return x - 5
like image 43
Netwave Avatar answered Oct 07 '22 00:10

Netwave