_sitebuiltins?

Steve D'Aprano steve+python at pearwood.info
Mon Sep 25 10:45:29 EDT 2017


On Mon, 25 Sep 2017 12:05 pm, Stefan Ram wrote:

> So when after
> 
> import builtins
> 
>   the expression
> 
> builtins.dir
> 
>   yields a value, then »dir« must be in »builtins«.


dir is in builtins *now*, but that doesn't tell you where it came from. Anything
can be added, or removed, from builtins.

py> import builtins
py> del builtins.len  # Don't do this unless you know what you are doing.
py> len('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'len' is not defined


In one sense, builtins is just an ordinary module, and like all modules it is
writable.

In another sense, it is special: Python always searches builtins before raising
NameError. Also, builtins is not a physical module on disk:

py> math.__file__
'/usr/local/lib/python3.5/lib-dynload/math.cpython-35m-i386-linux-gnu.so'

but: 

py> builtins.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'builtins' has no attribute '__file__'



>   Now, I was just curious whether I also can get the
>   same information directly from a name. If so, I would
>   like to publish this in my course just to clarify
>   the relationship between such names and their modules.

There is very little relationship between the object and the module you access
it though. For many functions, if you access it:

spam.foo()

then foo.__module__ will be 'spam'. But that's not a promise. It just means that
the foo function happened to have been created inside the foo.py or foo.so file
(or foo.dll on Windows?) but that isn't always the case.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list