How to call python function with optional parameters

I have the following function:

def create(self, name, page=5, opt1=False, opt2=False,
                        opt3=False,
                        opt4=False,
                        opt5=False,
                        opt6=False,
                        *parameters):

      

Is it possible to assign only one of the optional parameters and some * parameters? eg.

create('some name', opt4=True, 1, 2, 3) # I need 1, 2, 3 to be assigned to *parameters

      

Most of the time, I don't need to change the opt1 ... opt6 values, I only need to change one of them and assign another one *parameters

. So I'm looking for a way to avoid installing opt1 ... opt6 if I don't want to change their default.

+3


source to share


2 answers


In Python 3.x try putting parameters

before any of the default arguments, for example -

def create(self, name , *parameters, page=5, opt1=False, 
                                  opt2=False,opt3=False,
                                  opt4=False,opt5=False,
                                  opt6=False):
    print(parameters)
    print(page)
    print(opt4)

In [31]: create('C', 'some name', 1, 2, 3, opt4 = True)
(1, 2, 3)
5
True

      

Please understand that with this method you can only call arguments with a default value using named arguments.




For Python 2.x you can try using *parameters

and then **kwargs

for default parameters -

>>> def create(self, name, *parameters, **kwargs):
...     kwargs.setdefault('opt4',False)  #You will need to do for all such parameters.
...     print(parameters)
...     print(kwargs['opt4'])
... 
>>> create('C', 'some name', 1, 2, 3, opt4 = True)
(1, 2, 3)
True

      

Again, just a way to set values ​​for opt1...opt6

or page

etc. will use named arguments.

0


source


Well, for sure it's not nice, but you can probably work on variations of this



def create(name, page=5, opt1=False, opt2=False,
           opt3=False,
           opt4=False,
           opt5=False,
           opt6=False,
           *parameters):
    print(parameters)
    print(page)
    print(opt4)

myArgs = dict(zip(['page','opt1','opt2','opt3','opt4','opt5','opt6'],create.func_defaults))

myArgs['opt4']=True
create("MyName",**myArgs)

      

+1


source







All Articles