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

Christopher Barker pythonchb at gmail.com
Fri Apr 26 15:25:02 EDT 2019

Others have responded, but a note:

> 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

I am finding this very confusing as to how to generalize this:

How do we know that val_1 belongs to the "top-level" field_1, and val_2 is
in the nested dict with field_2?

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

but this makes it seem like that distinction is hard-coded -- so is the
nested dict is relevant?

> The more core syntax, which should be valid throughout the language,
would be to have statements like `x = y if cond`

we have the

x = y if cond else

expression already -- and an assignment HAS to be assigned to something, so
it seems what you want is:

x = y if cond else None

Maybe the "else None" feels like too much typing, but I prefer the
explicitness myself. (and look in the history of this thread for "null
coalescing" discussion, that _may_ be relevant.

The first of these intuitively reorganizes to `if cond: x = y`

then what do we get for x  `if not cond`? it ends up undefined? or set to
whatever value it used to have?

Frankly, I think that's a mistake -- you're going to end up with having to
trap a NameError or do a a hasattr() check later on anyway. It's generally
considered good practice to set a name to None if it isn't defined, rather
than not defining it.

> and `x[y if cond]` ... But the second is not as clear, with a likely
equivalent of `if cond: x[y] else raise Exception`.

assuming x is a dict, then you could do:

d[y if cond else []] = value

It's a hack, but as lists aren't hashable, you get an TypeError, so maybe
that would work for you?


In [16]: key = "Fred"
In [17]: value = "Barnes"
In [18]: d = {}

In [19]: # If the key is Truthy:
In [20]: d[key if key else []] = value

In [21]: d
Out[21]: {'Fred': 'Barnes'}

In [22]: # if the key is Falsey:
In [23]: key = None

In [24]: d[key if key else []] = value
TypeError                                 Traceback (most recent call last)
<ipython-input-24-170a67b9505a> in <module>()
----> 1 d[key if key else []] = value

TypeError: unhashable type: 'list'


Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190426/944ee5c0/attachment.html>

More information about the Python-ideas mailing list