r/badcode • • Apr 30 '22

python Looks like Python List Comprehension-phobia is a thing. This is a real commit by a teammate.

Post image
1.2k Upvotes

125 comments sorted by

View all comments

Show parent comment

2

u/JestemStefan May 29 '22 edited May 29 '22

Instead of

    if some_var:
        x = some_var
        # rest of code

You can do:

    if x := some_var:
        # rest of code

1

u/wtfzambo May 29 '22

Seems such a weak improvement :(

Is the second x scoped solely within the if statement?

So that if I call x outside of it I get NameError?

3

u/JestemStefan May 29 '22 edited May 29 '22

It's available in outer scode.

You can also do:

    if not (x := some_var):
        #some code
    
    print(x)  #works

It works like:

    x = some_var
    if x:
        #rest of code

Anyway. You save one line of code and you don't repeat yourself

1

u/wtfzambo May 29 '22

Then I really don't understand the purpose. Maybe I'm too stupid lol.

3

u/JestemStefan May 29 '22 edited May 29 '22

You can assign variable and use it in if statement at the same time.

You save line of code and you don't repeat yourself

Small QoL improvement.

3

u/wtfzambo May 29 '22

Yeah I get it.

What I don't get is all the fuss they had to go through to implement this, since I remember at the time, python devs were pretty polarized by this feature (as in, let's implement vs let's not).

It sounds such a minor improvement to even spend more than 5 minutes thinking about it. Unless I'm missing something crucial.

2

u/lyoko1 Oct 27 '22

it is nice to use inside dictionary values, this is an example inspired on some code i wrote a few hours ago with the walrus op:

blablabla.create(map(lambda record: {
    ...other key value pairs...
    'task_id': (task := get_task(record)).id,
    'project_id': task.project.id,
    ...other key value pairs...
}, records))

Again, this is not necessary perse, it is syntax sugar, and with one thing it is a bit senseless since you only save one line, but when you have a case like the above but with multiple values and inside a list comprehension or a map, it becomes very useful to make the code a little bit easier to read and easier to refactor in the future.

I use them from time to time, it looks nicer than having a wall of lines of variables that you preassign before a large if else chain to use in the comparation and in the code inside. And as the example has shown, it can also be used outside of ifs, you can use it inside a map or a comprehension to set values that depend on a value that you are computing inside the map/comprehension