8

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.

tscizzle
  • 11,191
  • 15
  • 54
  • 88
  • 2
    This will not set `parameters[user_device]` to `user_device` if `user_device` is something that evaluates to `False` in a boolean context that is not `None`, such as the empty string, `0`, an empty list or tuple, and so on. If you do not want this behaviour, change your check to `if user_device is not None`. – timgeb Jul 11 '14 at 17:48
  • 1
    There doesn't seem to be anything wrong with this way of doing it. Although you could just enter it into `parameters` as `None`. As long as you account for it being `None` down the line it should work fine either way. – kylieCatt Jul 11 '14 at 17:50
  • Ooh, good point. Turns out if it were any of those things I still would not want user_device in targeting_spec, so my statement "If a non-None value is provided..." was not technically accurate because things like "" or [] are also not needed by me, (like None). I will edit, and fix my variable names to match description. – tscizzle Jul 11 '14 at 17:53
  • Actually I will go with non-None, and thus change the check to be `if user_device is not None:` but that is a valid concern which I did not take into account before. – tscizzle Jul 11 '14 at 17:56
  • it would be nice if you could do something like `{'key1': value1, 'key2': value2 if value2, 'key3': value3}` – Ariel Aug 31 '17 at 08:50
  • Is it possible to do this in a way that does require `targetting_spec` to be mutable? – Awais Hussain May 03 '18 at 13:35

1 Answers1

5

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343