Python Forum
Exception of the day - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Forum & Off Topic (https://python-forum.io/forum-23.html)
+--- Forum: Bar (https://python-forum.io/forum-27.html)
+--- Thread: Exception of the day (/thread-37604.html)



Exception of the day - DeaD_EyE - Jun-29-2022

Error:
[{key: row for key, row in zip(("port", "state", "resolution"), parsed)} for parsed in [[data[0], f"{data[1]} {data[2]}", data[3]] if "primary" in (data := e.split()) else data[:3] for e in subprocess.run(["xrandr"], capture_output=True, encoding="utf8").stdout.splitlines() if " connected" in e]] ^ SyntaxError: assignment expression cannot be used in a comprehension iterable expression
Hypnotic
I was trying to push it further and further.

At some point, as I tried to put a list-comprehension inside a list comprehension, where the elements are a dictionary comprehension...
But there was the assignment expression as big problem. I guess it's not allowed to prevent bad side effects.

🛈 What I've learned: You can't use the walrus operator anywhere in nested inner list/set/dict comprehensions. As well, generator expressions.

Holy cow, that they were able to be so concise.


RE: Exception of the day - Gribouillis - Jun-29-2022

I wouldn't dare write such a line...


RE: Exception of the day - Gribouillis - Jun-30-2022

(Jun-29-2022, 06:05 PM)DeaD_EyE Wrote: {key: row for key, row in zip(("port", "state", "resolution"), parsed)}
can be simplified in
dict(zip(("port", "state", "resolution"), parsed))
In fact, the following version works for me
import subprocess

x = [dict(zip(("port", "state", "resolution"), parsed)) for parsed in [[data[0], f"{data[1]} {data[2]}", data[3]] if "primary" in data else data[:3] for data in (e.split() for e in subprocess.run(["xrandr"], capture_output=True, encoding="utf8").stdout.splitlines() if " connected" in e)]]

for item in x:
    print(item)