[Python] Mandatory keywords arguments

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    Some functions in Python standard library have (optional) keyword argument(s), but using them in the form of keyword arguments is optional , e. g.

    enumerate(iterable, start=1) # as keyword argument


    and

    enumerate(iterabele, 1) # as positional argument


    are both correct.

    But others explicitly forbid using their optional keyword arguments as positional, e. g. sorted():


    sorted(iterable, *, key=None, reverse=False)
    Return a new sorted list from the items in iterable.
    Has two optional arguments which must be specified as keyword arguments.​

    (See also PEP 3102 - Keyword-Only Arguments.)

    Why such decision for only few keyword arguments? What would be bad with such (incorrect) use:

    sorted(strings_list, len, True) # Incorrect, but why not allowed?

    Continue reading...

Compartilhe esta Página