Skip to content

Instantly share code, notes, and snippets.

@cassiel
Created February 19, 2012 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cassiel/1863525 to your computer and use it in GitHub Desktop.
Save cassiel/1863525 to your computer and use it in GitHub Desktop.
(ns oncotrees.util
(:import [org.python.core PyFloat PyInteger PyBoolean PyString
PyList PyInstance PyNone]
[java.util NoSuchElementException]))
(defn hashify [py-object]
(cond (instance? PyNone py-object) nil
(instance? PyInstance py-object)
(letfn [(retr [key] (.__getitem__ (.__dict__ py-object) key))
(de-iter [iter result]
(let [n (try
(.next iter)
(catch NoSuchElementException _ nil))]
(if (nil? n)
(reverse result)
(recur iter (cons n result)))))
(lookup [key]
(let [p (retr key)]
(condp = (class p)
PyFloat (.asDouble p)
PyInteger (.asInt p)
PyBoolean (.__nonzero__ p)
PyString (.asString p)
PyList (map hashify (de-iter (.iterator p) nil))
(hashify p))))]
(reduce (fn [m k] (assoc m (keyword k) (lookup k)))
(hash-map)
(.keys (.__dict__ py-object))))
:else py-object))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment