I was staring at a piece of Python code I produced, which, though correct, is ugly. Is there a more pythonic way of doing this?
r = self.get_pixel(x,y, RED)
g = self.get_pixel(x,y, GREEN)
b = self.get_pixel(x,y, BLUE)
t = function(r,g,b)
if t:
r2, g2, b2 = t
self.set_pixel(x,y,RED, r2)
self.set_pixel(x,y,GREEN, g2)
self.set_pixel(x,y,BLUE, b2)
The problem is the repetition of the method calls for get_pixel
and set_pixel
. For your information:
RED, GREEN, BLUE = range(3)
Also note that I'd like to preserve code clarity and cleanness.
As you are using self
, it appears that get_pixel
etc are methods of your class. Instead of list comprehensions and zip()
and other workarounds, look at the APIs and fix them. Two suggestions:
get_pixel_colors(x, y)
which returns a 3-tuple. Then you can write r, g, b = self.get_pixel_colors(x, y)
self.set_pixel_colors(x, y, r, g, b)
Even better, you can use the *args
notation:
old_colors = self.get_pixel_colors(x, y)
new_colors = function(*old_colors)
if new_colors:
self.set_pixel_colors(x, y, *new_colors)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With