why am I feeling so guilty about this? should I be feeling guilty about this?

#python #NestedLoops

Follow

@shine yeah, Python doesn't like this style. But it can be made more Pythonic:

- provide an empty list as a default to avoid checking for 'route_table' key
- no need to check for `if rtb['route']`, since an empty list just won't iterate
- do it all as a list comprehension to avoid repeatedly calling .append()

So:

public_route_tables = [
route['id']
for rtb in resource_by_type.get('route_table', [])
for route in rtb['route']
if route['id'] in INTERNET_GATEWAY_IDS
]

· · Web · 2 · 1 · 1

@isagalaev wow, that piece of code looks beautiful.

I actually didn't intend to ask for solutions. I only wanted to vent my guilt.

you are definitely a way better python programmer than I am. I would never come up with that code. thank you so much.

@isagalaev

> since an empty list just won't iterate
thanks, I did not think of it. that avoids one level of indentation.

> do it all as a list comprehension to avoid repeatedly calling .append()

actually, I did think of ( and tried ) list comprehension; but it did not work for me when I tried it. I will try it once again with your suggestion and see if it works.

/me goes off to copy-paste-code-I-found-on-the-internet 🏃

but thank you so much 🙏

@shine you bound to pick up a thing or two in 15 years :-)

List comprehensions with nested loops are admittedly rare, but there's nothing magical about them, these are the same loops you have in the original code.

@isagalaev but it looks a lot more beautiful than my stupid code.

And not only the looks, it works too! I had to change `route['Id']` to `rtb['Id']` to fit my logic, but it worked with copy-paste.

@shine make sure to add some tests :-)

Glad it worked. I obviously didn't have anything to run it against.

@isagalaev Well, you put in the effort of typing out code from an image, and without any context and it still worked! That shows the experience and mastery you have.

Re: tests - they are there, but they wouldn't catch such optimizations though.

Or can they? 🤔

@shine I didn't mean tests should catch optimizations, I just mean the new code shouldn't break on the same data, that's all.

cc @rune here's another way ( in the thread / previous toot ) to fix that 6-level stupidity that I made up.

credit to @isagalaev

Sign in to participate in the conversation
Mastodon

Server run by the main developers of the project 🐘 It is not focused on any particular niche interest - everyone is welcome as long as you follow our code of conduct!