I have a function create_group
with an optional parameter user_device=None
. If a non-None value is provided for user_device
, I want a dictionary targeting_spec
to include the key-value pair "user_device": user_device
, and if no non-None value is provided, I do not want targeting_spec
to include this key-value pair.
How I do it now:
def create_group(..., user_device=None, ...):
...
targeting_spec = {
...
}
if user_device:
targeting_spec["user_device"] = user_device
...
Is this an accepted way of doing this? If not, what is? I ask because this seems like the type of thing Python would love to solve elegantly.
Your approach is fine, provided you don't need to support empty values.
Consider passing in user_device=0
, for example. user_device
is not None
, but it is a falsey value.
If you need to support falsey values apart from None
, use is not None
to test:
if user_device is not None:
parameters["user_device"] = user_device
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With