Home > Software design >  How to keep the parameter by default on python
How to keep the parameter by default on python

Time:09-21

I know that we can give the parameter to the function, and we can call the function without parameter:

def printWords(text1="a", text2="b"):
   print('The text1 is "%s" and text2 is "%s"' % (text1,text2))
    
printWords()

Then, We can get the result

The text1 is "a" and text2 is "b"

We also can pass the result to override the default parameter

printWords("Apple") // The text1 is "Apple" and text2 is "b"
printWords("Apple","Banana") // The text1 is "Apple" and text2 is "Banana"

Then, How to do if I only want to change the text2 ? In this case we can pass the a into the function. But it is So messy if there are many parameters with long text, for example:

def curlSomthing(sslKey="MIICXAIBAAKBgQCRq88qPiw..............=",someText="BuDPuTMSUrwnophwzti8HRc6Z7SYaGnFHMVMrF/3f/TgdWd4UTH3397RA7m5I4gVNbFCA0xOTfh............",someSetting=False):
     ....
     ....
     ....
     ....

We can't copy and paste all the parameter every time we call the function. I know this is not a good way to define a function. But so many function like this in my company's code. I can't change all the function

Any solution ?

CodePudding user response:

Just specify the argument name as a keyword argument:

printWords(text2="Apple")

Then text1 would remain the same.

With your other messy function:

curlSomthing(someText="foo bar")
  • Related