3

I have the following code

import pandas as pd
df = pd.DataFrame(columns=['var1', 'var2','var3'])
df.loc[0] = [0,1,2]

def RS():
    x = 123
    y = 456
    z = 'And some more random shit'
    return x+y

def BS():
    x = -890
    y = (456*1)+90
    z = 'And some more random shit'
    return x-y

def MyCompute(srt, srt_string):
    df[srt_string] = srt()
    df['1min' + srt_string] = 1-df[srt_string]

MyCompute(srt=RS, srt_string='RS')
MyCompute(srt=BS, srt_string='BS')

Is there a way to avoid the double RS and double BS in calling the MyCompute function?

4 Answers4

7

Use the attribute __name__ :

def MyCompute(srt):
    df[srt.__name__] = srt()
    df['1min' + srt.__name__] = 1 - df[srt.__name__]

MyCompute(srt=RS)
MyCompute(srt=BS)
azro
  • 53,056
  • 7
  • 34
  • 70
1

Put your functions in a dictionary, then you can look up the function by name.

compute_dict = {"RS": RS, "BS": BS}
def MyCompute(srt_string):
    srt = compute_dict[srt_string]
    df[srt_string] = srt()
    df['1min' + srt_string] = 1-df[srt_string]
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Yes, you can use the __name__ attribute of a function, e.g. RS.__name__ instead of 'RS'

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Yes, you can just get the name of the function:

def MyCompute(srt):
    df[srt.__name__] = srt()
    df['1min' + srt.__name__] = 1-df[srt.__name__]

MyCompute(srt=RS)
MyCompute(srt=BS)
quamrana
  • 37,849
  • 12
  • 53
  • 71