Namespace

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Introduction

Namespaces are one honking great idea -- let's do more of those! --- Zen of Python, Tim Peters

I agree. Too bad people don't understand what namespaces are.

Isn't this just scope?

No. Scope is the set of rules that describe which name refers to which variable and which value.

What is a namespace, really?

Say you're in England. You hear someone talking about "boots". You think of what Americans call "trunks". That's namespaces.

The idea of namespaces are that you give things names, and then package up those names in something called a namespace. And then, down the road, you open up that package and start referring to those things by name again.

You can also say things like "the thing they call a 'boot' in England", but that's not the power of namespaces.

What's the catch?

The catch is that you can easily get confused. If you frequently fly between England and the US, you will find yourself, one day, referring to thing with the wrong name. Namespaces are great, but you can't switch namespaces too much.

Python

In Python, every file has its own namespace. This is the module object of the module represented by the file.

In Python, you can import the namespace from another module en masse', but this is discouraged. Rather, you should import things one at a time.

Except---when you're writing your own code and you're sharing lots of things between files. In these cases, use "from blah import *" as much as you like. Your files are, in a way, sharing one common namespace.

Javascript

Yuck.

Javascript has only one namespace, and everything starts there by default.

To solve this, you can create objects and refer to attributes of the object with '.' notation.

Some people use lexical scope to create a namespace for their module. It looks something like this:

var MyPackage = {};
(function() {
   var my_temp_var = 'whatever';
   MyPackage.fn = function() { ... };
})();

This gives you a workspace to work in that is cleaned up after initialization.

Java

Double yuck.

Java has a single namespace dictated by where the file lives on the path. It's a terrible mess. It's one of the reasons why I hate Java.

Perl

Perl has syntax to create a namespace with the 'package' declaration, but a single file can have multiple namespaces. Confusing. Just like the rest of perl. Normally people don't abuse this, though.

See Also