How will you compare namespaces in Python and C++?

PythonServer Side ProgrammingProgrammingC++

Namespaces in Python and C++ cannot really be compared. For example, in C++ −

// a.h
namespace ns {
    struct A { .. };
    struct B { .. };

If we were to do this −

#include "a.h"
using ns::A;

The point of that code is to be able to write A unqualified(ie, not having to write ns::A). Now, you might consider a python equivalent as −

from a import A

But regardless of the using, the entire a.h header will still be included and compiled, so we would still be able to write ns::B, whereas in the Python version, a.B would not be visible. The other C++ version,

using namespace ns;

also doesn't have a Python analogue. It brings in all names from namespace ns throughout the entire code-base - and namespaces can be reused. For example,

#include <vector>
#include <map>
#include <algorithm>
using namespace std; // bring in EVERYTHING

That one line is kind of equivalent to −

from vector import *
from map import *
from algorithm import *

at least in what it does, but then it only actually brings in what's in namespace std - which isn't necessarily everything.

Published on 21-Dec-2017 16:13:46