__builtin__ quote

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jan 7 02:24:32 CET 2009


En Tue, 06 Jan 2009 06:56:36 -0200, James Stroud <jstroud at mbi.ucla.edu>  
escribió:

> Steven Woody wrote:
>> On Tue, Jan 6, 2009 at 4:42 PM, James Stroud <jstroud at mbi.ucla.edu>  
>> wrote:
>>> py> import __builtin__
>>> py> __builtin__.abs is abs
>>>    True
>>  Does that mean someone did 'import * from __builtin__'  when python  
>> startup?
>
> In terms of the exact implementation of the cPython interpreter, I don't  
> know. But the interpreter behaves as if someone did just that. So there  
> is nothing wrong with thinking of it this way if it helps you understand  
> the interpreter.

Not exactly. Built-in names are "one step further" global names; it's not  
that builtin names populate by default the global namespace. As local  
names "hide" (or "shadow") global names, those global names "hide" builtin  
names. Those three namespaces are distinct, like onion layers (global and  
local namespaces are the same at the module level).

If the interpreter did the equivalent of "from __builtin__ import *",  
redefining builtin names would destroy them, but that's not the case:

# the builtin "abs" function
>>> abs(-3)
3
>>> abs
<built-in function abs>

# this one "hides" the builtin abs
>>> def abs(x):
...   return "Hi, I'm the abs() global function!"
...
>>> abs(-3)
"Hi, I'm the abs() global function!"
>>> abs
<function abs at 0x00B9F2F0>

# remove the global "abs"
>>> del abs

# we can access again the builtin "abs"
>>> abs(-3)
3
>>> abs
<built-in function abs>

--
Gabriel Genellina




More information about the Python-list mailing list