Jython, usa solo un método de Python de Java?

Al leer y usarEste artículo asume que tenemos una definición de objeto completa con objetos de clase y mapeo (proxy) de python a java.

¿Es posible importar solo un método (no definido dentro de una clase, pero usando una clase interna de python) desde un fragmento de código en python sin envolverlo en una definición de clase (sin usar el paradigma de fábrica descrito anteriormente)?

Me hubiera gustado hacer algún tipo defrom myPyFile import myMethod desde java, y luego use myMethod, directamente desde java (¿quizás como un método estático?)? Pero si esto es posible, no he encontrado ninguna pista de cómo hacerlo (las cosas de la interfaz descritas en el artículo pueden ser necesarias para decirle a Java cómo usar mi Método).

Atentamente.

EDITAR : Ahora estoy tratando conJython 2.5.2, por lo que puede depender de la versión y mucho más fácil en el futuro?

EDITAR: Abajo en respuesta a Daniel:

Aquí hay un código de muestra, para reproducir el error que recibo, ¡y también obtener un ejemplo funcional de su útil respuesta!

(Bueno, y agregue otra pequeña pregunta sobre la asignación a objetos Java desde unrendimiento -ed resultado de Python / Jython)

(@Joonas, Lo siento, modifiqué mi código y ahora no puedo volver al error que solía tener)

<code>import org.python.core.Py;
import org.python.core.PyList;
import org.python.core.PyTuple;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

interface MyInterface {
    public PyList getSomething(String content, String glue, boolean bool);
}
class MyFactory {

    @SuppressWarnings("static-access")
    public MyFactory() {
        String cmd = "from mymodule import MyClass";
        PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());

        PySystemState sys = Py.getSystemState();
        sys.path.append(new PyString("C:/jython2.5.2/Lib"));

        interpreter.exec(cmd);
        jyObjClass = interpreter.get("MyClass");
    }

    public MyInterface createMe() {
        PyObject myObj = jyObjClass.__call__();
        return (MyInterface)myObj.__tojava__(MyInterface.class);
    }

    private PyObject jyObjClass;
}


public class Main {

    public static void main(String[] args) {

    /*
// with only :
    PythonInterpreter interpreter = new PythonInterpreter();

     i get : 
Exception in thread "main" Traceback (most recent call last):
  File "<string>", line 1, in <module>
LookupError: no codec search functions registered: can't find encoding 'iso8859_1'

which is probably due to the : 
#!/usr/bin/env python
# -*- coding: latin-1 -*-

// yes i am from France, so my - sorry for that - bad english ;) and have to deal with non 127 ascii chars :)
     */

    PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());

    PySystemState sys = Py.getSystemState();
    sys.path.append(new PyString("C:/jython2.5.2/Lib"));

    interpreter.exec("from mymodule import getSomething"); 
    PyObject tmpFunction = interpreter.get("getSomething"); 
    System.err.println(tmpFunction.getClass()); 
    MyInterface i = (MyInterface) tmpFunction.__tojava__(MyInterface.class); 
    System.err.println(i.getSomething("test", " - ", true));
    for (Object x : i.getSomething("test", " - ", true)) {
        System.out.println(x);
        // How can i get back an equivallent of the Python _"for (a, b) in getSomething:"_ 
        // with _"a"_ being PyUnicode or better String, and _"b"_ being boolean ?
    }

    // ^^ so adapting Daniel Teply solution works ! Thanks to him... 
    // BTW the part below did not work : but i may have missed or/and also mixed many things :/
    // i feel Jython damned hard to dive in :/ 
    // and really hope that the sample that i post and answers that i get will help others to swim!

    try {
        MyFactory factory = new MyFactory();
        MyInterface myobj = factory.createMe();

        PyList myResult = myobj.getSomething("test", " - ", true);
        System.out.println(myResult);
    }
    catch (Exception e) {
        System.out.println(e);
        // produce a : java.lang.ClassCastException: org.python.core.PySingleton cannot be cast to MyInterface
        // EDIT : see below last edit, this error may be due to my forgotten heritage from interface in the python code!
    }

    System.exit(-1);
    }
}
</code>

Parte de Python: (mymodule.py)

<code>#!/usr/bin/env python
# -*- coding: latin-1 -*-

class MyClass:
    def __init__(selfself):
        pass
    def getSomething(self, content, glue = '', bool = True):
        for x in range(5):
            yield (glue.join(map(str, (content, x, chr(97 + x))))), bool
        #return list()

def getSomething(content, glue = '', bool = True):
    print "test"
    myclass = MyClass()
    return list(myclass.getSomething(content, glue, bool))

def main():
    test()

if __name__ == "__main__":
    main()
</code>

EDITAR :

Respondiéndome parcialmente, por la pregunta interna (comentarios internos):
(en realidad siento que mi respuesta y el código son feos, pero funciona y parece estar bien para des-tupla No sé si hay una mejor manera Jythonic de hacerlo, si es así, estoy realmente interesado :))

<code>for (Object x : i.getSomething("test", " - ", true)) {
    System.out.println(x);
    // How can i get back an equivallent of the Python _"for (a, b) in getSomething:"_ 
    // with _"a"_ being PyUnicode or better String, and _"b"_ being boolean ?

    // answering myself here :
    PyTuple mytuple = (PyTuple) x; // casting back x as PyTuple, can we have a java equivalent to _`(a, b) = x_ ? not sure...
    PyObject a = mytuple.__getitem__(0);
    PyObject b = mytuple.__getitem__(1);
    String aS = a.toString(); // mapping a unicode python string to java is as simple?
    boolean bB = b.toString().toLowerCase().equals("true");
    System.out.println(mytuple + "[" + aS + "][" + b + "][" + bB + "]");
</code>


EDITAR:

Respondiéndome a la parte sobre "producir un:"java.lang.ClassCastException: org.python.core.PySingleton no se puede convertir en MyInterface"... la mayoría de mis malentendidos y errores se debieron al hecho de que me había olvidado de manejar Java desde la parte de Python. (vea mi código arriba, lo dejo sin corregir sobre este hecho porque no era mi pregunta principal, y en su forma real, es una respuesta de trabajo sobre esta pregunta principal, muchas gracias a Daniel y Joonas que me ayudaron a entender). Así que para el paradigma de la fábrica, uno debeNO olvide agregar la importación adecuada a su archivo Python:

<code>from testjython.interfaces import MyInterface #// defining method inside a MyInterface.java

class MyClass(MyInterface):
    [...]
</code>

Otra dificultad que tuve fue manejar correctamente la importación y los paquetes. Por cierto, agregar este código al código superior producirá unTypeError: no se puede convertir a org.python.core.PyList pero esta es otra preocupación ...

Respuestas a la pregunta(2)

Su respuesta a la pregunta