确定函数调用者的名称空间

时间:2013-11-11 22:56:08

标签: clojure

我试图准确地确定函数调用者的命名空间。看起来*ns*由调用堆栈顶部的命名空间决定。

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=>

我还可以依赖其他一些元数据,还是需要手动指定?

2 个答案:

答案 0 :(得分:1)

这是不可能的。在repl中,*ns*始终设置为repl所在的命名空间;在运行时它通常是clojure.core,除非有人设置它的麻烦,这是不常见的。

答案 1 :(得分:1)

我不确定你的完整用例是什么,但从你的例子判断你想要#'bar / ask返回自己的命名空间而不是返回一个解析当前命名空间的函数。你可以简单地使用def而不是defn。以下是您所做的一个示例:

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"

希望这有帮助!

相关问题