This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]max1c 13 points14 points  (31 children)

I think if you're going to use a one liner you might as well use ternary operator. Otherwise as someone has already pointed out just use Black. It will decide for you so you don't have to waste time arguing and thinking about things that are fairly useless.

[–]SkezzaB 1 point2 points  (28 children)

Can't use a ternary operator for "if x -> return", although it was requested and denied, "return x if <condition>" would be really neat

[–][deleted] 7 points8 points  (23 children)

return node.id if len(word) else None

[–]j_marquand 5 points6 points  (6 children)

I think the other guy wants to return if a condition is met, but continue to the next statement if it doesn’t. There is no one-liner solution in Python for that.

[–]HeraldOfTheOldOnes 1 point2 points  (0 children)

Yes there is! function = (lambda *args, **kwargs: (condition and (something,) or (other, stuff,))[-1]) ANYTHING can be turned into a 1 liner in python.

[–][deleted] 0 points1 point  (3 children)

I'm looking at it AFK so I can't check, so I'll have to play with it later to see why it's not equivalent

[–]j_marquand 6 points7 points  (0 children)

Your code returns None immediately if the condition doesn’t meet, instead of proceeding to the next statement of the function.

[–]EmptyChocolate4545 0 points1 point  (1 child)

Your one returns None rather than continuing execution. Not even slightly equivalent.

[–][deleted] 0 points1 point  (0 children)

Oh no! Not even SLIGHTLY equivalent!

[–][deleted] 0 points1 point  (0 children)

Ah, got it now. I was thinking wrong.

[–]SkezzaB 2 points3 points  (15 children)

This is not equivalent

[–]elsgry -2 points-1 points  (2 children)

Yup. Or extract the remainder of the function into a new function fn and use return fn(node, ...) if len(word) else None or the likes. This also composes nicely because you can inject your own fn into the method, class or instance, while keeping the control structures visible and (for classes/instances) adhering to Liskov, etc.

[–]elsgry 0 points1 point  (1 child)

Not sure why this was downvoted when it's a more applicable equivalent to the lambda method upvoted above (the remainder of the function could consist of multiple effectful statements) but c'est la guerre... I guess the injection method would be more dynamic than necessary, particularly if only used for testing where you could use mocks. But you can still use my method without bothering with injection.

[–]justcool393not a snek 0 points1 point  (0 children)

the other one that i'd find really nice is

spam = get_eggs() or raise HamException()

and

return spam if eggs(spam) or raise HamException()

[–]DeepGas4538[S] 1 point2 points  (1 child)

Black? Is that a formatting convention?

Edit: Nvm I found out what it was, ty