1

We have the following function call used at multiple places within close proximity:

func(param1, param2, param3, param4, param5)

I would like to use

funccall() 

in all the places.

Is there a notion of macros? Partials with all the arguments given (marked answer as correct) is correct and it works if all the subsequent calls are in the same scope.

What if the scenario is like this:

A():
func(p1,p2,p3,p4,p5) # 3 times

B():
func(p1,p2,p3,p4,p5) # 2 times

C():
func(p1,p2,p3,p4,p5) # 4 times

Using partial:

A():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 3 times

B():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 2 times

C():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 4 times

Ideal (if convention is followed in code and readability is not a problem)

macro funccall() = func(p1,p2,p3,p4,p5)

A():
funccall() # 3 times

B():
funccall() # 2 times

C():
funccall() # 4 times
Zoe
  • 27,060
  • 21
  • 118
  • 148
Kumar Deepak
  • 473
  • 4
  • 18
  • 1
    What do you mean by "within close proximity" ? Please provide a representative example (nb: no macros in Python, and from what you describe partial application the obvious solution). – bruno desthuilliers Sep 26 '18 at 08:07
  • Python has no notion of macros: in a dynamic language there is not much to distinguish a macro invocation from a function call. You could package your multiple parameters into a data structure (a dict, say, or a named tuple) and redefine `func()` to accept one parameter instead of many; or to accept the data structure (default: empty data structure) with individual parameters as optional overrides. – BoarGules Sep 26 '18 at 08:12
  • Partial with all the arguments given will achieve this, so accepting that answer. Still is there a macro kind of way to do this? – Kumar Deepak Sep 26 '18 at 08:48

2 Answers2

2

This question is related to this one

As the answer provided by MattH, you can use functools.partial

from functools import partial
funccall = partial(func, 1, 2, 3, 4, 5)
funccall()
zxch3n
  • 387
  • 3
  • 9
1

set default parameters and only call the function explicitely with those parameters which are different from the default parameters!

e.g. def func(param1=0, param2="abc", param3=0.3) for definition

and result = func(param1=3) when calling.

(not tested, but I see no reason why this shouldn't work!)

Cut7er
  • 1,209
  • 9
  • 24
  • this is helpful, but in my case the parameters have to be passed everytime. Only thing we know is that the variable names of parameters are same for every call, which calls for an abstraction. – Kumar Deepak Sep 26 '18 at 09:00