Motivation: In c++ I often used namespaces to group symbols within a header
file. The intention being to ensure code using these symbols remains easy to
read in regard which symbol is called. Omitting the namespace might be
convenient for writing code but makes reading it harder. If needed, the
namespace can explicitly be renamed by a user (or made non-required).
In Nim, I know `{.pure.}` for enums, which comes quite close to what I want.
But I think this works only for enums, not other kinds of symbols (procs,
variables, constants, types, ...).
Customizing the import statement works only for the file with that import
statement. When exporting those symbols, the requirement for that namespace is
lost. (At least as far as I know.)
Occasionally, I saw Nim code with prefixes in each symbol's name to group them
together. As far as I know, there is no (reasonable) way to change that prefix
as a user of that code. Also I find it a lot harder to read
`thisIsTheNamespaceAndSomewhereInTheMiddleTheSymbolsNameBegins` then
`thisIsTheNamespace.AndSomewhereInTheMiddleTheSymbolsNameBegins`.
A small toy example for a package "somePackage" with these two files
# helpers.nim
let onlyWithNamespacePlease* = "hello"
# somePackage.nim
from helpers import nil
# issue#1: no idea how to export `helpers` while preserving the need for a
namespace
export helpers
Run
When using somePackage
import somePackage
echo helpers.onlyWithNamespacePlease # namespace is required
#issue#2: must not compile since required namespace is omitted
#echo onlyWithNamespacePlease
Run
In case it helps, the c++ equivalent with the three desired behaviors (require
namespace by default, allow renaming namespaces, make namespace non-required)
//helpers.hpp
namespace helpers {
std::string const onlyWithNamespacePlease = "hello";
}
//somePackage.hpp
#include helpers.hpp
Run
// using somePackage
#include somePackage.hpp
// namespace is required
std::cout << helpers.onlyWithNamespacePlease << std::end;
// rename namespace
namespace renamedNamespace = helpers;
std::cout << renamedNamespace.onlyWithNamespacePlease << std::end;
// make namespace optional
using namespace helpers
std::cout << onlyWithNamespacePlease << std::end;
Run
Finally the question: What is the Nim way to get similar results?