by behnamoh · 4y ago · 0 comments
(a++ if a==b else b++) + 1
Or something like this (borrowed from https://stackoverflow.com/questions/65024477/walrus-operator...): from datetime import datetime
timestamps = ['30:02:17:36', '26:07:44:25',
'25:19:30:38','25:07:40:47']
timestamps_dt = [
datetime(days=day,hours=hour,minutes=mins,seconds=sec)
for i in timestamps
day,hour,mins,sec := i.split(':')]
But this type of stuff is always greeted with Python's inflexible syntax. Recently, I learnt about Rackets's idea that "everything is expression" on (https://beautifulracket.com/appendix/why-racket-why-lisp.htm....) and was blown away to realize these are valid Racket codes: ((if (< 1 0) + *) 42 100)
or (+ 42 (if (< 1 0) 100 200))
The second one has an equivalent in Python: 42 + (100 if 1 < 0 else 200)
But the first one does not: 42 (+ if 1 < 0 else *) 100
> SYNTAX ERROR.Maybe it's time for me to get my hands dirty with Lisp.
Please rewrite this as
if a == b:
a += 1
else:
b += 1
and don't leave the other developers (or yourself two months from now) scratching their head about what that code does. You have more important things to do than trying to understand your code again and again.Furthermore, does that + 1 at the end run before or after the ++?
> (a++ if a==b else b++) + 1
I had to try it out (with a syntax that can run)
>>> a = 1
>>> b = 2
>>> (a+1 if a == b else b+1) + 1
4 # the expression evaluates to 4, wtf!
>>> a
1
>>> b
2
But this is not a += 1 which is syntax error and the point of your post. a = 1
b = 2
((a := a + 1) if a == b else (b := b + 1)) + 1
although that's a lot to cram into a single line IMO.The closest I could come up with for the second example is this (noting that the datetime constructor requires both the year and month):
from datetime import datetime
timestamps = [
"2022:04:30:02:17:36",
"2022:04:26:07:44:25",
"2022:04:25:19:30:38",
"2022:04:25:07:40:47",
]
datetimes = [
datetime(*map(int, timestamp.split(":")))
for timestamp in timestamps
]
That said, it'd probably be better to use datetime.fromisoformat() or datetime.strptime() rather than manual parsing.And you could maybe use the operator module[1] for the last example, like this:
import operator as op
(op.add if 1 < 0 else op.mul)(42, 100)
[1] https://docs.python.org/3/library/operator.htmlPresuming this is indeed what behnamoh meant by a++, that `(a++ if a==b else b++) + 1` would be better written `++a if a==b else ++b`, which would then become the clearer `(a := a + 1) if a == b else (b := b + 1)`.
Why? This is absurdly unreadable. Why not create a function, give it a name, and use simple if/else constructs. Help the next developer out so they don't need to figure out your tricky expression.
>
> 42 (+ if 1 < 0 else *) 100
Of course it does:
from operator import add, mul
(add if 1 < 0 else mul)(42, 100) from operator import add, mul
(add if 1 < 0 else mul)(42, 100)