7

What are the closest concepts in Python to namespace and using statements in C++?

3
  • 1
    Python also has namespaces, and the with context manager is broadly similar to using, I think. Commented Apr 19, 2015 at 13:52
  • I don't know C++ very well, but isn't using in C++ like import in Python? Commented Apr 19, 2015 at 14:02
  • @KSFT Not really. C++ doesn't have modules, so it has no equivalent to a python import. Commented Apr 19, 2015 at 14:44

2 Answers 2

5

There isn't really an analogue. Consider this simple header:

// 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 (as opposed to 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 more expansive version:

using namespace ns;

definitely has no Python analogue either, since that brings in all names from namespace ns throughout the entire code-base - and namespaces can be reused. The most common thing I see beginner C++ programmers do is:

#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.

Sign up to request clarification or add additional context in comments.

1 Comment

Semi-OT: Your answer made it to tutorialspoint – without adequate attribution, of course. I guess this is a violation of CC BY-SA license.
4

The closest equivalent to the namespace directive found in other languages is the Implicit Namespace Packages facility described in PEP 420 and introduced in Python 3.3. It allows for modules in multiple locations to be combined into a single, unified namespace rather than forcing the import of the first valid candidate found in sys.path.

There is no direct equivalent of using; importing specific names from a module adds them to the local scope unilaterally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.