1

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 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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])

Comments

2

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])

2 Comments

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...
Ahh yes, if it's not returning the value, you're stuck with zeros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.