[Python-ideas] Syntax to conditionally define a field in a dict

MRAB python at mrabarnett.plus.com
Fri Apr 26 14:30:46 EDT 2019


On 2019-04-26 16:56, Sebastian Kreft wrote:
> 
> On Fri, Apr 26, 2019 at 11:07 AM Joshua Marshall <j.marshall at arroyo.io 
> <mailto:j.marshall at arroyo.io>> wrote:
> 
>     Hello all,
> 
>     I have a use case where I need to send a `dict` to a module as an
>     argument.  Inside of this, it has a multi-level structure, but each
>     field I need to set may only be set to a single value.  Fields must
>     be valid, non-empty strings.  It looks a lot like the following in
>     my code:
> 
>     ```
>     def my_func(val_1, val_2):
>          return {
>              "field_1": val_1,
>              "next_depth": {
>                  "field_2": val_2
>              }
>          }
>     ```
> 
>     What I want to do is:
>     ```
>     def my_func(val_1, val_2):
>          return {
>              "field_1": val_1 if val_1,
>              "next_depth": {
>                  "field_2": val_2 if val_2
>              }
>          }
>     ```
> 
> If val_2 here evaluates to falsey, will next_depth still be defined? 
>  From the code I would say that no. But your use case may require to not 
> define the next_depth subdict without any values, as that may break the 
> receiver expectations (think of JSON Schema).
> 
 From the code I would say yes. If you didn't want the subdict, you 
would've written:

     def my_func(val_1, val_2):
          return {
              "field_1": val_1 if val_1,
              "next_depth": {
                  "field_2": val_2
              } if val_2
          }

> 
>     Or:
>     ```
>     def my_func(val_1, val_2):
>          return {
>              if val_1 : "field_1": val_1,
>              "next_depth": {
>                  if val_2: "field_2": val_2
>              }
>          }
>     ```
> 

     def my_func(val_1, val_2):
          return {
              if val_1 : "field_1": val_1,
              if val_2: "next_depth": {
                  "field_2": val_2
              }
          }

[snip]

The first form is too easily confused with the ternary 'if'.

In Python, an expression never starts with an 'if', so the second form 
would be a better syntax for an optional entry.


More information about the Python-ideas mailing list