问题
I'm trying to accurately determine the namespace of a function's caller. Looks like *ns*
is determined by the namespace at top of the call stack.
user=> (ns util)
nil
util=> (defn where-am-i? [] (str *ns*))
#'util/where-am-i?
util=> (ns foo (:require [util]))
nil
foo=> (util/where-am-i?)
"foo"
foo=> (ns bar)
nil
bar=> (defn ask [] (util/where-am-i?))
#'bar/ask
bar=> (ask)
"bar"
bar=> (ns foo)
nil
foo=> (util/where-am-i?)
"foo"
foo=> (bar/ask)
"foo"
foo=>
Is there some other meta data I can rely on or do I need to specify this manually?
回答1:
This is not possible. In the repl, *ns*
is always set to the namespace in which the repl is; at runtime it is usually clojure.core, unless someone goes to the trouble to set it, which is uncommon.
回答2:
I'm not sure what your complete use case is, but judging from your example you want #'bar/ask to return its own namespace instead of returning a function that resolves the current namespace. You could simply use def instead of defn. Here is an example following on from what you did:
util=> (in-ns 'bar)
#<Namespace bar>
bar=> (def tell (util/where-am-i?))
#'bar/tell
bar=> (in-ns 'foo)
#<Namespace foo>
foo=> (refer 'bar :only '[tell])
nil
foo=> tell
"bar"
Hope this helps!
来源:https://stackoverflow.com/questions/19917633/determine-namespace-of-a-functions-caller