Skip to content

Commit 410aad5

Browse files
authored
add 2 Init lifecycle hooks (#234)
* added 2 lifecycle methods before and after tnitialisation * document the 2 hooks * more idiomatic
1 parent 9298549 commit 410aad5

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

src/libpython_clj2/python.clj

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@ user> (py/py. np linspace 2 3 :num 10)
4242

4343
(set! *warn-on-reflection* true)
4444

45-
46-
4745
(defn initialize!
4846
"Initialize the python library. If library path is not provided, then the system
4947
attempts to execute a simple python program and have python return system info.
@@ -64,6 +62,24 @@ user> (py/py. np linspace 2 3 :num 10)
6462
{:python-executable \"env/bin/python\"}
6563
```
6664
65+
Additionaly the file can contain two keys which can can refer to custom hooks
66+
to run code just before and just after python is initialised.
67+
Typical use case for this is to setup / verify the python virtual enviornment
68+
to be used.
69+
70+
```
71+
:pre-initialize-fn my-ns/my-venv-setup-fn!
72+
:post-initialize-fn my-ns/my-venv-validate-fn!
73+
74+
```
75+
76+
A :pre-initialize-fn could for example shell out and setup a python
77+
virtual enviornment.
78+
79+
The :post-initialize-fn can use all functions from ns `libpython-clj2.python`
80+
as libpython-clj is initialised alreday andc ould for example be used to validate
81+
that later needed libraries can be loaded via calling `import-module`.
82+
6783
The file MUST be named `python.edn` and be in the root of the classpath.
6884
With a `python.edn` file in place, the `initialize!` function may be called
6985
with no arguments and the options will be read from the file. If arguments are
@@ -97,6 +113,7 @@ user> (py/py. np linspace 2 3 :num 10)
97113
(let [python-edn-opts (-> (try (slurp "python.edn")
98114
(catch java.io.FileNotFoundException _ "{}"))
99115
clojure.edn/read-string)
116+
_ (some-> python-edn-opts :pre-initialize-fn requiring-resolve (apply []))
100117
options (merge python-edn-opts options)
101118
info (py-info/detect-startup-info options)
102119
_ (log/infof "Startup info %s" info)
@@ -132,10 +149,10 @@ user> (py/py. np linspace 2 3 :num 10)
132149
(io-redirect/redirect-io!))
133150
(finally
134151
(py-ffi/unlock-gil gilstate))))
152+
(some-> python-edn-opts :post-initialize-fn requiring-resolve (apply []))
135153
:ok)
136154
:already-initialized))
137155

138-
139156
(defmacro stack-resource-context
140157
"Create a stack-based resource context. All python objects allocated within this
141158
context will be released at the termination of this context.

0 commit comments

Comments
 (0)