Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any problem with namespacing clojure keywords in a non-existent namespace?

Should I feel wary about creating clojure keywords which have non-existent namespaces?

An example would be :foo/bar, where namespace foo doesn't actually exist. This seems to be possible because these keywords behave like literals. I couldn't find any problems doing this in the REPL, but I'm concerned about possible problems with AOT compilation.

like image 949
Rob Lachlan Avatar asked Jun 07 '10 23:06

Rob Lachlan


1 Answers

A namespace will in fact not be created simply because a keyword or symbol is encountered which would "belong" to it, as the following interaction at a fresh REPL illustrates:

; SLIME 2010-05-06
user> (-> (.getNamespace :user/foo) symbol)
user
user> (-> (.getNamespace :user/foo) symbol the-ns)
#<Namespace user>
user> (-> (.getNamespace :bar/foo) symbol the-ns)
; java.lang.Exception: No namespace: bar found

However, this is no cause for worry. A keyword's or symbol's "namespace" field is just an interned string; there is no reference back to the corresponding namespace object involved even if one exists. In fact, as can be seen above, the .getNamespace method of keywords and symbols returns a string and one has to jump a few hops to get to the actual namespace from that.

Trying to resolve a namespace-qualified symbol with the resolve function is safe too. That's regardless of whether the namespace actually exists; if it doesn't, nil is returned, as in the case where it does exist, but holds no Var of the given name. ns-resolve, in contrast, will throw an exception like the one mentioned in the snippet from the REPL above if it can't find the given namespace.

like image 81
Michał Marczyk Avatar answered Oct 05 '22 23:10

Michał Marczyk