3

I have been looking into the use of *args and **kwargs and i have consulted a number of relevant posts, which provide quite a few interesting examples:

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

*args and **kwargs?

How to expand a list to function arguments in Python

Converting Python dict to kwargs?

However, the above threads do not provide a clear answer to the question of what is the best way of flexibly using the same (keyword) arguments and their default values in multiple functions? And by flexibly i mean being able to also define additional (keyword) arguments in each function on a case by case basis.

Essentially, i would like to avoid manually defining the same arguments in each function over and over again, instead only focusing on the additional ones that are required in each function.

For example, instead of:

def testfunction1(voltage=0, state="bleedin", status=0):
    ...do something...

def testfunction2(voltage=0, state="bleedin", status=0, action="VOOM"):
    ...do something else...

(note: status could be anything like a list or a tuple or an array.)

I would like something along the following lines:

d = {"voltage": 0, "state": "bleedin", status} 

def testfunction1(**d):
    ...do something...

def testfunction2(**d, action="VOOM"):
    ...do something else...

I could then call each function like:

testfunction1(voltage=5, state="healthy")

or specify the arguments directly like:

testfunction1((5, "healthy", statuslist)

Hopefully this is clear but i would happy to clarify further if necessary.

  • 4
    Have you considered using a `class` ? you could pass all the common arguments to the `__init__` method and any additional ones to the methods themselves. – JoseKilo Mar 19 '18 at 16:10
  • 2
    You can’t write this the way you’re trying, but you could do the equivalent with a function-creating function (or with a decorator). But I don’t think it’s a good idea. Help, inspect, IDEs, etc. won’t know the signature of your functions—and, worse, neither will a human reader without making some additional effort. Depending on what you actually want to do, a better design might be making these all methods of a class, or creating a class that wraps up all this status and gets passed as an argument. – abarnert Mar 19 '18 at 16:13

1 Answers1

0

Here is a method using classes as mentioned in the comments.

class test:
    def __init__(self,voltage = 5, state = "bleedin", status = 0):
        self.arguments = {'voltage' : voltage, 'state' : state, 'status': status}
    #You essentially merge the two dictionary's with priority on kwargs
    def printVars(self,**kwargs):
        print({**self.arguments,**kwargs})

Here is a sample run

>>> a = test()
>>> a.printVars(status = 5, test = 3)
{'voltage': 5, 'state': 'bleedin', 'status': 5, 'test': 3}
Tristhal
  • 110
  • 8