Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
d[x](some_df)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading