Home > other >  Anyway to prefill the function argument with other argument
Anyway to prefill the function argument with other argument

Time:06-06

I know that there are some similar topis on this, but I wonder that if there is a string argument that depend on other argument within a python function, is there an proper way of doing it(like the one below, but doesn't work)

def printMsg(defaultMsg=f"Hello {name}", name="John"):
    print(defaultMsg)

CodePudding user response:

Or, if you want to be flexible specifying the message format

def printMsg(msg_fmt='Hello {name}', **kwargs):
    print(msg_fmt.format(**kwargs))

and then

printMsg(name='John')

CodePudding user response:

What about this?

def printMsg(name="John", defaultMsg=None):
    
    if defaultMsg is None:
        defaultMsg = f'Hello {name}'
    
    print(defaultMsg)
  • Related