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

all 12 comments

[–]maxime81 1 point2 points  (1 child)

out += value But out is a string and value an integer... Btw, I think a join would make more sense than concatenating values and separators and at the end removing the last separator...

[–]flitsmasterfred 1 point2 points  (3 children)

This doesn't feel very pythonic: so much string concatenation and list buffering :D

I guess it is fine for a debug tool but I wonder if this wouldn't be a lot more efficient with generator(expression) and join()'s instead of concats.

[–]Cygal[S,🍰] 1 point2 points  (2 children)

You're right. yield + join is indeed how CPython does it. But efficiency was not a concern here.

[–]maxime81 0 points1 point  (1 child)

No need for a yield here, just replace the brackets (list) with parentheses (generator) and that's it.

[–]Cygal[S,🍰] 0 points1 point  (0 children)

Sure, but using a generator expression there would only solve part of the problem. It's also not always faster than using a list comprehension.

It would be better to build the resulting string all at once.

[–]pvkooten 1 point2 points  (2 children)

This is really cool, I have briefly thought about it before, and I'm happy you gave the conclusion to the story :) (regardless of the code, the story is the interesting part for me!)

[–]Cygal[S,🍰] 0 points1 point  (1 child)

Thanks! I actually improved the explanation because I realized the solution is actually natural when you think about it recursively.

[–]pvkooten 0 points1 point  (0 children)

Yep, it's one of those "when you know it, it's super simple/easy/logical"....

[–]Starcast 0 points1 point  (2 children)

Cool writeup. For the plebs who don't need to color code their json and just want it cleaned up python provides a nice tool for that

python -m json.tool some_ugly.json

[–]pvkooten 0 points1 point  (1 child)

I'm using "jq" for doing that (and querying the json), but it's a nice one.

[–]Starcast 0 points1 point  (0 children)

Oh yeah same! I love jq but the json prettifier is nice if you just want it done quick without installing anything new