cursive

RAJKUMAR 2025-04-18T20:05:45.358169Z

Hi is it possible to make a conditional def in one namespace visible in another namespace

RAJKUMAR 2025-04-18T20:06:52.639929Z

consider I have 3 namespaces debug, if-def-demo and main as below 1.) debug namespace

(ns debug)

(def enabled? true)
2.) if-def-demo namespace
(ns if-def-demo)

(def mseq [ "a" "b" "c"])

(if (debug/enabled?)
  (def my-var mseq))
3.) in main namespace
(ns main)

(println if-def-demo/my-var)

RAJKUMAR 2025-04-18T20:07:26.265019Z

if-def-demo/my-var is not visible in main namespace

RAJKUMAR 2025-04-18T20:07:58.211869Z

raspasov 2025-04-18T20:13:03.304749Z

The fact that a static analysis tool like Cursive cannot find it is usually a sign that things are getting a bit too complex. I personally like to use a combination of (defonce ...) and atoms for such cases instead of conditional (def ) or conditional-anything…

raspasov 2025-04-18T20:18:25.130899Z

(ns debug)

(defonce enabled? (atom true))
(ns if-def-demo)

(def mseq ["a" "b" "c"])

(defonce my-atom (atom nil))

;; also ideally hide this inside a fn, (defn init [ ] ...) or similar
;; top-level side effects can create complex hard-to-debug behavior during loading or compilation phases
(if @debug/enabled?
  (reset! my-atom mseq))

❤️ 1
raspasov 2025-04-18T20:19:59.343499Z

If you need something more… “proper” for managing stateful stuff like that, this is a good choice https://github.com/stuartsierra/component

raspasov 2025-04-18T20:21:39.428889Z

But I still end up using the defonce + atom simple solution more often than not

RAJKUMAR 2025-04-18T20:21:57.037049Z

Thanks @raspasov

👍 1