Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of repeating a method call on different finite arguments

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.

like image 898
Manuel Araoz Avatar asked Aug 14 '10 22:08

Manuel Araoz


1 Answers

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:

  1. Write another method get_pixel_colors(x, y) which returns a 3-tuple. Then you can write r, g, b = self.get_pixel_colors(x, y)
  2. Similarly: 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)
like image 58
John Machin Avatar answered Nov 15 '22 00:11

John Machin