Lrx
Lrx

Reputation: 422

Is it possible to perform conditional unpacking in python?

I'm currently doing an interface between several API in a python project.

really basically, at some point, I have to call a method from a "Builder" object. There are two types of builders, a GetBuilder and an AggregateBuilder (I'm using the Weaviate API for people wondering). They both allow me to setup an hybrid search as follow :

search_settings = {param_1: value_1, param_2: value_2, ...}

get_builder = get_builder.with_hybrid(**search_settings)
aggregate_builder = aggregate_builder.with_hybrid(search_settings)

Notice that the only difference between the two syntax is the dict unpacking for the GetBuilder.

My question is general: is there a clean way to perform conditional unpacking ?

So far, the only options I have found are :

1 if - else

aggregate: bool
builder: GetBuilder | AggregateBuilder

if aggregate:
    builder = builder.with_hybrid(settings)
else:
    builder = builder.with_hybrid(**settings)

Efficient, clear, but I feel It's redundant

2 using eval

aggregate: bool
builder: GetBuilder | AggregateBuilder

builder = eval("builder.with_hybrid({}settings)".format("**"*(not aggregate)))

Works, but unclear and the eval function just feels wrong to use

Is there another way to perform a conditional unpacking cleanly ?

Upvotes: 0

Views: 82

Answers (1)

dkruit
dkruit

Reputation: 145

Option 1 looks good to me. If you want to make a single call to builder.with_hybrid() you could do the following:

if aggregate:
    args, kwargs = [settings], {}
else:
    args, kwargs = [], settings

builder.with_hybrid(*args, **kwargs)

Upvotes: 0

Related Questions