Skip to content

add 2 Init lifecycle hooks #234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 27, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/libpython_clj2/python.clj
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ user> (py/py. np linspace 2 3 :num 10)

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



(defn initialize!
"Initialize the python library. If library path is not provided, then the system
attempts to execute a simple python program and have python return system info.
Expand All @@ -64,6 +62,24 @@ user> (py/py. np linspace 2 3 :num 10)
{:python-executable \"env/bin/python\"}
```

Additionaly the file can contain two keys which can can refer to custom hooks
to run code just before and just after python is initialised.
Typical use case for this is to setup / verify the python virtual enviornment
to be used.

```
:pre-initialize-fn my-ns/my-venv-setup-fn!
:post-initialize-fn my-ns/my-venv-validate-fn!

```

A :pre-initialize-fn could for example shell out and setup a python
virtual enviornment.

The :post-initialize-fn can use all functions from ns `libpython-clj2.python`
as libpython-clj is initialised alreday andc ould for example be used to validate
that later needed libraries can be loaded via calling `import-module`.

The file MUST be named `python.edn` and be in the root of the classpath.
With a `python.edn` file in place, the `initialize!` function may be called
with no arguments and the options will be read from the file. If arguments are
Expand Down Expand Up @@ -97,6 +113,7 @@ user> (py/py. np linspace 2 3 :num 10)
(let [python-edn-opts (-> (try (slurp "python.edn")
(catch java.io.FileNotFoundException _ "{}"))
clojure.edn/read-string)
_ (some-> python-edn-opts :pre-initialize-fn requiring-resolve (apply []))
options (merge python-edn-opts options)
info (py-info/detect-startup-info options)
_ (log/infof "Startup info %s" info)
Expand Down Expand Up @@ -132,10 +149,10 @@ user> (py/py. np linspace 2 3 :num 10)
(io-redirect/redirect-io!))
(finally
(py-ffi/unlock-gil gilstate))))
(some-> python-edn-opts :post-initialize-fn requiring-resolve (apply []))
:ok)
:already-initialized))


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