MightyPork
MightyPork

Reputation: 18861

Readable code in python 3 with function calls (lots of parens)

I used to like Python for the readability, but after moving to Pythion 3, that seems to be gone.

Ponder this:

print([k for k in hist_full_g(img.scale(12,44))])

Maybe it's not as much Python 3 that's the problem, but my coding style, but w/e.

Look at all the parens!

Now obviously I could split it into several local variables, but that would be looong.

img_scaled = img.scale(12,44)
histogram = hist_full_g()
histogram_array = [k for k in ]
print(histogram_array)

I can also add spaces around parens - actually I sometimes do that, but it's kinda ugly and I've read it's bad practice.

print( [ k for k in hist_full_g( img.scale(12, 44) ) ] )

How should I write it to be readable and "good quality"?

I'm not talking about this one example, I mean in general. My Python often looks like Lisp, and I don't think it should.

Upvotes: 1

Views: 83

Answers (1)

user2555451
user2555451

Reputation:

You can make your code more pythonic by replacing the list comprehension with a simple call to list:

print(list(hist_full_g(img.scale(12,44))))

There is never a good reason to do:

[x for x in iterable]

since list(iterable) yields the same result.

You might also want to use two lines to break up the code a little:

hist = hist_full_g(img.scale(12, 44))
print(list(hist))
# or
hist = list(hist_full_g(img.scale(12, 44)))
print(hist)

You'll notice too that I added a space after , in the call to img.scale. Having spaces separate function arguments keeps everything from looking so compact. In fact, this style is used all throughout PEP 0008 (the official style guide for Python code).


Edit:

Perhaps you would like to use a for-loop:

value = img.scale(12, 44)
for f in hist_full_g, list, print:
    value = f(value)

The readability may not be great, but it gets rid of all the parenthesis.

Upvotes: 5

Related Questions