Namespace: dir(), globals(), locals(), vars()

In most languages, the namespace is decided at compile time, and there is no way to determine which variables are in it unless you try to use them and the program doesn't compile. With Python, you can see the variables in the namespace, and you can see what variables a given object exposes.

dir()

dir([object]) returns a list of namespace variables. If no arguments are passed, it returns a list of names in the current namespace; otherwise, it returns a list of an object's attribute names.

Here are two examples of dir() showing what's in the current namespace in a function and in a module, respectively:

 >>> var1, var2, var3, var4 = 1,2,3,4 >>> dir() ['__builtins__', 'var1', 'var2', 'var3', 'var4'] ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.