Skip to content

Commit 853a336

Browse files
committed
refactor init and add with-interpreter macro
1 parent a778870 commit 853a336

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

src/clojure_python/core.clj

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,33 @@
11
(ns clojure-python.core
2-
(:use (clojure.core.*))
32
(:import (org.python.util PythonInterpreter)
43
(org.python.core.*)))
54

6-
;; instantiate a python interpreter in the python namespace
7-
(def interp (new org.python.util.PythonInterpreter))
5+
(declare ^:dynamic *interp*)
86

9-
(defn init
10-
"this may later take keywords and initialize other things
11-
for now it is just used to specify python library paths"
12-
([libpath]
13-
(doto clojure-python.core/interp
14-
(.exec "import sys")
15-
(.exec (str "sys.path.append('" libpath "')"))))
16-
([libpath & more]
17-
(init libpath)
18-
(apply init more)))
7+
(defn append-paths!
8+
"appends a vector of paths to the python system path"
9+
[libpaths]
10+
(.exec *interp* "import sys")
11+
(doseq [p libpaths]
12+
(.exec *interp* (str "sys.path.append('" p "')")))
13+
*interp*)
14+
15+
(defn init
16+
"Establish a global python interpreter. it is intended to only be called
17+
once. Alternatively, only use with-interpreter."
18+
[{:keys [libpaths] :as options}]
19+
(defonce ^:dynamic
20+
^{:doc "root binding serves as global python interpreter"}
21+
*interp*
22+
(org.python.util.PythonInterpreter.))
23+
(append-paths! libpaths))
24+
25+
(defmacro with-interpreter
26+
"Dynamically bind a new python interpreter for the calling context."
27+
[{:keys [libpaths] :as options} & body]
28+
`(binding [*interp* (org.python.util.PythonInterpreter.)]
29+
(append-paths! ~libpaths)
30+
~@body))
1931

2032
(defmacro py-import
2133
"define a library using the same name it has in python

0 commit comments

Comments
 (0)