[Python-ideas] Syntax to conditionally define a field in a dict
Joao S. O. Bueno
jsbueno at python.org.br
Sat Apr 27 11:24:59 EDT 2019
Calling upon ol' Guidos Time Machinne:
In [31]: def create(val1):
...: data = {
...: **({"val1": "me here"} if val1 else {})
...: }
...: return data
...:
In [32]: create(False)
Out[32]: {}
In [33]: create(True)
Out[33]: {'val1': 'me here'}
Now, please, just move to the next request to the language.
I think the in-place star exapanding, along with the inline if like above
can make out
for all of your use-cases. If it can't, then expect xpression assignment-s
(the `a:=1` from PEP 572,
comming in Python 3.8) to cover for the rest - as you can define variables
inside the `if` expressions
like the above which could be re-used in other `if`s (or even in
key-names), further down the dictionary)
So, seriously - On one hand, Python's syntaxalready allow what you are
requesting.
On the other hand, it makes use of a syntax that is already little used (in
place star-expansion for mappings),
to a point that in this thread, up to here, no one made use of it.
Threfore, IMHO, it demonstrates that adding arbitrary syntaxes and
language features ultimatelly fills the language
with clutter very few people ends up knowing how to use - - we should now
work on what
is already possible instead of making the language still more difficult to
learn .
(respasting the code so you can further experiment):
def create(val1):
data = {
**({"val1": "me here"} if val1 else {})
}
return data
On Fri, 26 Apr 2019 at 21:22, Christopher Barker <pythonchb at gmail.com>
wrote:
> 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?
>
> 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
> }
> }
>
> 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?
>
> example:
>
> 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'
>
> -CHB
>
>
>
>
> --
> Christopher Barker, PhD
>
> Python Language Consulting
> - Teaching
> - Scientific Software Development
> - Desktop GUI and Web Development
> - wxPython, numpy, scipy, Cython
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190427/704af324/attachment-0001.html>
More information about the Python-ideas
mailing list