[Python] Pythonic way to get the first passed kwarg without knowing its name? [duplicate]

Discussão em 'Python' iniciado por Stack, Agosto 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function, which has a signature like this:

    def func(**kwargs):


    The user of that function will call the function with zero or one keyword arguments. If the caller passes one argument, the name will be foo_id, bar_id, baz_id etc., but I don't know the exact name. The value of the passed argument will an arbitrary integer. I still want to take that argument's value and use it.

    Currently I'm doing it like this, but I was wondering would there be a cleaner way to achieve this:

    def func(**kwargs):
    if kwargs:
    target_id = list(kwargs.values())[0]
    else:
    target_id = None

    # use target_id here, no worries if it's None


    I'm using Python 3.8, so backwards compatibility is not an issue.

    Continue reading...

Compartilhe esta Página