Search code examples
pythonpython-3.xkeyword-argument

Pythonic way to get the first passed kwarg without knowing its name?


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 he passes one argument, the name will be foo_id, bar_id, baz_id etc., but I don't know the exact name he will use. The value of the passed argument will be some interger. 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.


Solution

  • Here we are

    def func(**kwargs):
        target_id = next(iter(kwargs.values()), None)
    
        print(target_id)
    
    
    func(name_id='name')
    func(value_id='value')
    func(test_id='test')
    func()
    
    

    Outputs

    python test.py
    name
    value
    test
    None