5

If I have a module Test and if I need to list all the functions in them, I do this:

import Test
dir(Test)

Unless I import the module I won't be able to use the functions defined in them.

But all the functions in __builtin__ module can be used without importing. But without import __builtin__ I am not able to do a dir(__builtin__). Does that mean we use the functions without importing the entire module?

from __builtin__ import zip

Is it something like the above? But if I do del zip, I get

NameError: name 'zip' is not defined

Can anyone please explain this behavior?

bdhar
  • 21,619
  • 17
  • 70
  • 86
  • 3
    In CPython, you could do `dir(__builtins__)` without importing anything, but that's an implementation detail of CPython. – Sven Marnach Mar 16 '11 at 12:11

3 Answers3

8

As explained in the Python language docs, names in Python are resolved by first looking them up in the local scope, then in any enclosing local scope, then in the module-level scope and finally in the namespace of the built-ins. So built-ins are somehow special-cased. They are not imported in your module's scope, but if a name is not found anywhere else, Python will look it up in the scope __builtin__.

Note that you can access the contents of this scope without importing it. A portable way to do this is

import sys
print(dir(sys.modules["__builtin__"]))

In CPython, this also works

print(dir(__builtins__))

but this is considered an implementation detail and might not be available for other Python implementations or future versions.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

when python interpreter start, it will by default execute something like

from __builtin__ import *

which allows you to use all the functions/attributes defined inside __builtin__ module

However to use __builtin__ symbol itself, you need to do

import __builtin__

this is how import statement syntax works.

rodney
  • 281
  • 1
  • 3
  • 6
1

I'm by no means knowledgeable about python, but maybe dir(__builtins__), with an "s", is what you're after?

Works for me on plain Python 3.1.

Erika
  • 416
  • 5
  • 14
  • No. I am talking about `__builtin__` module without an "s". http://docs.python.org/library/__builtin__.html. I am not talking about the `CPython` implementation. – bdhar Mar 17 '11 at 05:18