tags:

views:

370

answers:

3

I am writing jython application with eclipse SWT/JFace. I have to pass float array to java object to get back some values from it. I am using jarray package for it. Is there more pythonic way to do it?

bounds = zeros(4, 'f')
# from java org.eclipse.swt.graphics.Path.getBounds(float[] bounds)
path.getBounds(bounds)
# from java org.eclipse.swt.graphics.Rectangle(int x, int y, int width,int height)
rect = Rectangle(int(round(bounds[0])), 
                     int(round(bounds[1])),
                     int(round(bounds[2])),
                     int(round(bounds[3])))
+3  A: 

Maybe. First, you can reduce the code a bit:

bounds = map(lambda v: int(round(v)), bounds)

This avoids the repeated cast. My next step would be to create a helper method to turn the array into Rectangle, so you don't have to repeat this code:

def toRectangle(bounds):
    bounds = map(lambda v: int(round(v)), bounds)
    return Rectangle(bounds[0], bounds[1], bounds[2], bounds[3])

That would leave you with:

rect = toRectangle(path.getBounds(zeroes(4, 'f'))

Alternatively, create a helper function that directly accepts the path.

Or you could monkey patch Path:

def helper(self):
    bounds = zeros(4, 'f')
    self.getBounds(bounds)
    bounds = map(lambda v: int(round(v)), bounds)
    return Rectangle(bounds[0], bounds[1], bounds[2], bounds[3])

org.eclipse.swt.graphics.Path.toRectangle = helper

rect = path.toRectangle()

Note that this might be slightly wrong. If it doesn't work, look at classmethod() and new.instancemethod() for how to add a method to a class on the fly.

Aaron Digulla
+4  A: 

The use of list comprehensions is considered more pythonic these days:

rounded = [int(round(x)) for x in bounds]

This will give you a list of rounded ints. Of course you could assign this to bounds instead of using "rounded"

bounds = [int(round(x)) for x in bounds]

And on our mailing list Charlie Groves pointed out that the whole thing can be exploded with the * operator like this:

rect = Rectangle(*[int(round(x)) for x in bounds])
Frank Wierzbicki
This * ('explode operator') is very useful stuff, thanks!
Darius Kucinskas
+2  A: 

It's also worth pointing out that there's no need to use zeros to create an array. You can just call getBounds with a Python iterable containing instances that can be converted to the proper type:

path.getBounds([0, 0, 0, 0])
Charlie Groves
Well the problem is that void getBounds(float[] bounds) method (java native method of org.eclipse.swt.graphics.Path class) expects arrays of float numbers, return values are written to this array...
Darius Kucinskas
Ahh yes, if it's not returning the value, you're stuck with zeros.
Charlie Groves