python function signature reuse with variations

1 week ago 12
ARTICLE AD BOX

I have two functions with 100% identical (and lengthy) signatures, but slight variations in internal code.

I'd like to use the first-class-object nature of functions to reuse the signature, and then use the name of the called function to do some conditional branching inside the common code.

What's the most pythonic way to accomplish this?

I've tried a few different documented options to get the name of the current function from within a function, but, none of these will get the called function name, i.e. f1 vs f2 in this example:

import inspect def commonFuncCore(a=None,b=None,c=3): # print(f'funcName:{commonFuncCore.__name__} a:{a} b:{b} c:{c}') # print(f'funcName:{commonFuncCore.__qualname__} a:{a} b:{b} c:{c}') print(f'funcName:{inspect.currentframe().f_code.co_name} a:{a} b:{b} c:{c}') f1=commonFuncCore f2=commonFuncCore print('calling f1:') f1() print('calling f2:') f2()

Is it better to add an argument that specifies the hardcoded function name? The following code gives the desired output - is there a better way?

def commonFuncCore(a=None,b=None,c=3,funcName='COMMON'): # print(f'funcName:{commonFuncCore.__name__} a:{a} b:{b} c:{c}') # print(f'funcName:{commonFuncCore.__qualname__} a:{a} b:{b} c:{c}') # print(f'funcName:{inspect.currentframe().f_code.co_name} a:{a} b:{b} c:{c}') print(f'funcName:{funcName} a:{a} b:{b} c:{c}') # f1=commonFuncCore # f2=commonFuncCore def f1(*args,**kwargs): commonFuncCore(*args,**kwargs,funcName='f1') def f2(*args,**kwargs): commonFuncCore(*args,**kwargs,funcName='f2') print('calling f1:') f1(a=1,b=2,c=5) print('calling f2:') f2()

which gives the desired output:

calling f1: funcName:f1 a:1 b:2 c:5 calling f2: funcName:f2 a:None b:None c:3
Read Entire Article