FAQ Binding C to Python Namespaces

From DANSE

Namespaces

Problem

I use a third-party library that has a function named "log", but the compiler complains that log is already defined in "math.h". I don't want to change the name in the third-party library, and I need math.h. What to do?

Solution

Namespaces.

The problem is, every name in a C program must be defined once. No more, no less. That means that you can't have two objects, functions, variables etc. with the same name. This is a problem in large scale projects: since we use words from everyday language, where meanings are ambiguous, we often end up wanting to use the same word to describe two different objects or functions. Classic examples are "vector" to mean an array numbers and "vector" to mean a first-rank tensor, or "orange" the color and "orange" the fruit.

The solution to this problem is namespaces. Namespaces get around this problem by limiting the scope in which a name is defined. One can use the same name for two different entities as long as those names are not in the same namespace.

In C++, a namespace is declared as follows:

namespace colors
{
    class Orange{};
} // colors:: (always nice to tell the reader what just closed)
namespace fruit
{
    class Orange{};
} // fruit::

Now programmers using this code can specify exactly which Orange they have in mind:

bool isTasty( fruit::Orange const & orange){return orange.tasty;}

For full details on C++ namespaces, see Stroustrup, The C++ Programming Language, or an introductory text like Milewski, C++ in Action.

In Python, every module is a namespace. This is incredibly convenient, so much so that it takes C++ programmers a while to get used to that fact and quit giving mile long names to everything. For more information, see an introductory Python text, such as Lutz & Ascher, Programming Python.

You can use namespaces with Python bindings.

Personal tools
Document Uploads/Links