When importing a module, in the imported module one usually doesn't know if a specific name is defined in the importing module. Is there a way for the imported module to refer to a name only if it is defined in the importing module? E.g.
Importing module
import IGM
var VERSION = "1.0a"
Imported module (IGM)
if someTest(VERSION): echo VERSION
Use declared, e.g.:
when declared(ident):
...
or:
when declared(module.ident):
...
@Jehan: That's what I was looking for. Thanks!
@Jehan: Sorry, I was too quick: I get: ...: undeclared identifier: 'VERSION' when compiling a.nim.
a.nim
import b
const VERSION = "1.0"
su()
b.nim
proc su*() =
if defined(VERSION): echo VERSION
But wait, some trees seem to be broken... Using:
module a
import b
const VERSION = "2.b"
su()
module b
when isMainModule:
const VERSION = "1.a"
proc su*() =
echo "In su()..."
when declared(VERSION):
echo VERSION
when isMainModule:
su()
I get for a: In su()..., and for b: In su()... 1.a.
When compiling a.nim I get: a.nim(3, 7) Hint: 'VERSION' is declared but not used [XDeclaredButNotUsed] Obviously a.VERSION is eliminated by the compiler. If I reference a.VERSION somewhere in a the prog works as intended.
How would I prevent the elimination of a.VERSION?
Maybe not related but I had a problem similar to this and solved it by using "include" instead of "import".
In my case I wanted a "global" name defined in one file which was used by multiple modules which obviously just won't work using import for reasons @araq just listed.
Different solution, don't use it because environment vars are bad (tm) which is why I keep mentionin this solution (?):
import os
const VERSION* = getEnv("MYPROG_VERSION")
You seem confused about scope ... as with any programming language you might be familiar with, proc su uses the VERSION in the lexical scope of its definition, which is the one defined as "1.a". If you want it to use the one in the scope of its use, then make su a template, not a proc, and you get
$ a
In su()...
2.b
$ b
In su()...
1.a