Extending Jython


How do I create Java classes that emulate Jython Dictionaries and Sequences?

In order to emulate Dictionaries and Sequences, first your Java class must "extend" the org.python.core.PyObject class. The following methods can then be defined on your class in order to emulate these basic Jython types:

Additionally, you might want to throw the org.python.core.Py.KeyError object if you have any exceptions (Note, you need not declare the Java method as throwing anything.)

How do I emulate Jython object attribute access with a Java class?

You can develop your own Java class that emulates Jython objects by first extending the org.python.core.PyObject class. Then, implement the following methods on your Java class:

You may also want to raise exceptions using the org.python.core.Py.AttributeError error class. (Note, you do not need to declare that the method throws this class.)

As in CPython, "a = foo.bar" calls the findattr method on foo, "foo.bar = 'baz'" calls the setattr method on foo, and "delattr(foo, 'bar')" calls the delattr method on foo.

If you plan on storing functions as attributes of your Java object (so that you could say "foo.bar('baz', 'fizzle')", be forwarned that Jython *may or may not* call the findattr method to find the function object depending on the number/types of parameters. You should, additionally, implement the following methods:

How do I support *args and **kw in Java methods?

(thanks to Finn Bock for the information)

In Jython (note, this does not work in JPython), you can support keyword arguments on Java methods by defining the method like so (the parameters are the important point):

The keywords array contains all of the keywords for the keyword-defined arguments. For example, if you called foo with:

args would be: [1, 2, 3, 4, 5] and keywords would be: ['four', 'five'] (an array of 2 elements.)

Additionally, you can use the experimental argument parser org.python.core.ArgParser to deal mapping these two arrays. Consult the Javadocs (or source) for further details on org.python.core.ArgParser.