I am familiar with Python's import
mechanism (no expert though). I am not at all familiar with the modules mechanism that C++ has finally received in C++20. Despite them being two very different languages, I am sure that many idioms I am used to have with Python's import
can be approximated by C++'s module mechanism. Can you help me find (approximate) equivalents or explain why there are no close similarities between different ways an import can be done in Python?
From what I've read, Python's from foobar import *
should roughly be equivalent to C++'s import foobar;
. That is, all public symbols from foobar
become available for use at the top-level namespace. Are there any principal differences between them though?
Python's import foobar
makes symbols available, but they are all put inside a namespace foobar
. Can the same thing be achieved in C++, i.e. results of import are contained within a namespace?
Python's from foobar import barbaz
makes only a single symbol barbaz
visible. Can C++'s import
be instructed to operate on a limited number of external symbols, instead of importing the whole contents of the module?
Finally, from foobar import barbaz as qux
imports a symbol and makes it available under a different name. Can the same effect be achieved for C++ imports?
C++ modules don't have much in common with Python modules.
In particular, modules in C++ are completely orthogonal to namespaces. They replace/extend the header file and unit compilation mechanism, not the namespace mechanism.
import XY;
does not imply anything about whether or not entities from the module can be named with an unqualified name, nor does it permit using XY
to address the entities with a qualified name.
A name in the module can be part of any namespace just like in old C++. An import
directive can't be used to selectively import entities or to give them new names.
What you have in mind in your questions is more similar to various constructs using the using
and namespace
keywords in C++. The can be used to make names from a namespace available unqualified in the current namespace and to alias namespaces and some entities. However, even then, this is distinctly different from Python, because it can't be used to make declarations visible in the first place (which is what header files and modules are for) and because it doesn't generally work the same for all entities (e.g. using
can be used to alias types but not functions).