On Sun, Jan 24, 2010 at 11:26 PM, rob <r.p.l...@gmail.com> wrote: > Hi, > > I was wondering if anyone has tried somehow calling Jython functions > from within Clojure, and how you went about doing this if so. I have > not used Jython, but I would imagine the Jython interpreter can be > invoked in the same way as any other java code, and Python programs > can be run within it. However I wonder if it would be possible to > somehow call individual python functions from Clojure. Like I said, I > have not tried this yet, so it might actually be straightforward and > obvious. I'm just wondering if anyone has tried doing this. >
It's possible. We're doing it a little right now (we're mainly going the other way, calling Clojure from Jython with Clojure embedded in a JSR223-ish environment) — see this thread http://groups.google.com/group/clojure/msg/f878d7a32125ce58?hl=en for a hint. You end up having to wrap up the guts of Jython's Java interface which is actually fairly small. In our environment, where you can mix languages and where Jython's namespace is automatically propagated into Clojure for you, you have something like: // python def banana(x, y): return "x is %s, y is %s" % (x, y) // clojure (defn java2py [x] (into-array PyObject (map (fn [n] (. org.python.core.Pyjava2py n)) x))) (defn call-jython [x & y] (.__tojava__ (.__call__ x (java2py y)) Object)) (println (call-jython banana 5 "b")) Please pardon the Clojure code — I'm a Jython expert, but a total Clojure amateur. Ultimately, given a PyFunction, you need to invoke PyObject __call__(PyObject[] x) on it, thus you need to wrap (Py.java2Py) the arguments and unwrap (.__tojava__) the return value. Building on this "foundation" we can also instantiate objects and call methods: // python class Something: def callMe(self, x, y): print "callMe called %s %s " % (x,y) return 10+x+y // clojure (println (call-jython (.__getattr__ (call-jython Something) "callMe") 5 5)) As you can see Jython's classes never appear Java side. So Clojure's java interop is thwarted (you can't (.callMe ...) something) I'd be fascinated to see somebody who actually knows Clojure throw down that fantastic macro that makes these two kinds of calls pretty. Meanwhile I'm having fun learning my way towards it. Marc. -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en