How to use unquoted keyword-only function args in Python

Viewed 24

It is easy to create optional arguments in a function by specifying a default in the def.

for example sorted([1,3,2],reverse=True)

if I were defining this function I might say

def sorted(l:list, reverse:bool=False)

is there any way to define a function's parameters so that I can specify keywords without values? Simply mentioning the keyword makes it true. If there were I could define a function that accepts this

sorted([1,3,2],reverse)

I tried using **kwargs but apparently, it only accepts keywords that are included with values.

1 Answers

The closest to what I was looking for would be to use an Enum

import enum

class SortDirection(enum.Enum):
    REGULAR = None
    REVERSE = 2

def sorted(l:list, reverse:SortDirection=None):
    print(reverse)

sorted([], SortDirection.REVERSE)

So the above program outputs

SortDirection.REVERSE
Related