Safe to import __builtin__ ?

M

mrstevegross

Is it generally safe to explicitly import __builtin__ in python? That
is, my code reads like this:

=== foo.py ===
import __builtin__
....
print __builtin__.type('a')
=== EOF ===

It seems like it should be a safe import, but I just want to make
sure.

Thanks,
--Steve
 
M

mrstevegross

Why do you want to import it?
Seehttp://docs.python.org/library/__builtin__.html

I'm using a weird python environment that overloads a few builtin
functions. In order to run them, I need to explicitly invoke
"__builtin__.foo()" to make sure I get the real builtin version, not
the overloaded one.

--Steve
 
B

Benjamin Peterson

mrstevegross said:
Is it generally safe to explicitly import __builtin__ in python? That
is, my code reads like this: ....

It seems like it should be a safe import, but I just want to make
sure.

Yes, that's fine. I'm not sure why you don't just use type(), though.
 
M

mrstevegross

Yes, it's safe (and this is what the ‘__builtin__’ module is intended
for: <URL:http://docs.python.org/library/__builtin__>).

Be careful, though: there's a separate name, ‘__builtins__’, that is
*not* meant to be imported. It's also implementation-specific, so
shouldn't be relied upon. My advice: don't use ‘__builtins__’ at all,
but be aware that it exists so you spell ‘__builtin__’ correctly.

Thanks

--Steve
 
S

Steven D'Aprano

Yes, that's fine. I'm not sure why you don't just use type(), though.

I'm not sure why you think type() is a substitute for __builtin__. Here's
a typical use-case for __builtin__:


import __builtin__
def map(*args): # shadow a built-in
# pre-processing goes here
result = __builtin__.map(*args)
# post-processing goes here
return result


How does type() help you?
 
R

Robert Kern

I'm not sure why you think type() is a substitute for __builtin__. Here's
a typical use-case for __builtin__:


import __builtin__
def map(*args): # shadow a built-in
# pre-processing goes here
result = __builtin__.map(*args)
# post-processing goes here
return result


How does type() help you?

It doesn't in that sense. The example that Benjamin elided used
__builtin__.type() for no discernible reason (unlike your example which creates
a shadow function that overrides the builtin version). Benjamin was asking what
the motivation was, since it was not evident.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,290
Messages
2,571,453
Members
48,131
Latest member
AntoniaSep

Latest Threads

Top