I need to parametrize a method in Python

I want to do the following:

def apply_indicator(df, indicator="rsi"):
    print("first one")

def apply_indicator(df, indicator="ichimoku"):
    print("second one")

so that the indicator keyword would parametrize the method

I tried if statement over indicator parameter which is phoney though.

Method overloading is not a solution neither. Python seems to confuse the two function.

>Solution :

You appear to be trying to do Haskell-style pattern-matching on the arguments. For example, the following is valid Haskell:

apply_indicator df "rsi" = 1
apply_indicator df "ichimoku" = 2

Then apply_indicator something "rsi" == 1 and apply_indicator somethign "ichimoku" == 2.

Python does not support this kind of function definition. If you want one function, you need to do the matching inside the function, mostly simply with an if statement:

def apply_indicator(df, indicator):
    if indicator == "rsi":
        print("first one")
    elif indicator == "ichimoku":
        print("second one")

However, a function that does two different things based on explicit examination of one of its arguments is an anti-pattern. Your caller already has to decide what argument to pass to apply_indicator; they can just as easily decide which of two functions to call instead.

def apply_rsi(df):
    print("first one")

def apply_ichimoku(df):
    print("second one")

If you feel the need to "index" your set of parameter by a given argument, you can do that with a dict that maps the intended argument to the correct function:

d = {"rsi": apply_rsi, "ichimoku": apply_ichimoku}
x = ...  # rsi or ichimoku

Leave a Reply