Jython anonymous/nested classes vs. method pointers

I’ve been wondering if Python peeps ever use nested classes, which seem to work well in my small experiments. I have a feeling though, that simulating anonymous classes isn’t a very Pythonic thing to do since you have the ability to pass around references to methods or global functions. This is the feature that is “missing” ;) in Java that was the motivation for anonymous classes.

So my question is, which pattern is better to use in Jython? Probably the method pointers (or references… I don’t know what is the preferred term in Python). The bad news is that there seem to be restrictions on assigning method pointers to methods in Jython instances of Java classes like, say, Thread.

Here’s an example:


import java.lang as lang

class NestedThreadGen:
    def get(self):

        class NestedRunnable(lang.Runnable):
            def run(self):
                print 'Jython is a fun, shiny toy'

        return lang.Thread(NestedRunnable())

class PointerThreadGen:

    def get(self):
        t = lang.Thread()
        #WARNING, THIS WON'T RUN
        t.run = self.run
        return t

    def run(self):
        print 'Jython is a fun, shiny toy'

NestedThreadGen().get().start()
PointerThreadGen().get().start()

Here, I try both methods… simulating an anonymous class (it’s not really anonymous, just nested… but it prety much follows the pattern), and using a method pointer to create a Thread instance and run it. Unfortunately, the second technique (PointerThreadGen) doesn’t work:


Jython is a fun, shiny toy
Traceback (innermost last):
  File "test.py", line 27, in ?
  File "test.py", line 17, in get
TypeError: can't assign to this attribute in java instance: run

It appears that you can override methods in Java classes in Jython, and you can implement methods in Java interfaces in Jython… but you can’t assign method/function references to them.


About this entry