Zum Inhalt

Arguments and keyword arguments in functions

When defining functions, you can either name arguments or keyword arguments that are supposed to be passed to it.


The following is a function that expects one argument:

def say(msg):

# The following is valid

say('Hello python!')
say(msg='Hello python msg entered as keyword argument')
The following function only uses keyword arguments with defaults. It has an inner function that deals with how to format the message.

def say_something(msg=None, uppercase=False, capitalize=True):
    if not msg:

    def transform_msg(text):
        if uppercase:
            return text.upper()
        elif capitalize:
            return text.capitalize()
        return text

    return transform_msg(msg)

print(say_something('a sentence'))

# the first parameter is entered as argument here
say_something('foobar', uppercase=False)

# if all are entered as keywords, the order does not matter
say_something(uppercase=True, msg='big!')

# This does not work, you can not enter keyword arguments followed by arguments
say_something(uppercase=True, 'hey!')

# Short version of the above
def say_something(msg=None, uppercase=True, capitalize=True):
    if not msg or not any((uppercase, capitalize)):
        return msg
    return msg.uppercase() if uppercase else msg.capitalize()

# Version that relies on python internals getting the transformation by string name
def say_something(msg, *transformations):
    if not transformations:
        return msg
    for internal_str_func in transformations:
        msg = getattr(msg, internal_str_func)()
    return msg

# First call lower then capitalize on the text
text = say_something('aAAA BBB ccc', 'lower', 'capitalize')
assert text == 'Aaaa bbb ccc'


A good principle with if else is also to handle the cases that you want to get out of the way first, so that you can continue with less indentation in nested.'

Letztes Update: June 27, 2022
Erstellt: June 27, 2022