Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 554
ruohola Avatar asked Oct 28 '25 05:10

ruohola


1 Answers

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
like image 177
Alexandr Shurigin Avatar answered Oct 29 '25 18:10

Alexandr Shurigin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!