[Python-Dev] __import__ problems

Steven D'Aprano steve at pearwood.info
Sat Nov 29 02:18:01 CET 2008

On Sat, 29 Nov 2008 05:20:01 am Alex Martelli wrote:
> On Fri, Nov 28, 2008 at 9:47 AM, Steven D'Aprano <steve at pearwood.info> 
> > On Sat, 29 Nov 2008 03:30:49 am Christian Heimes wrote:
> > ...
> >
> >> May I point you to the two leading underscores? The name
> >> '__import__' clearly suggests that the function is part of
> >> Python's internals. By definition all attributes of the form __*__
> >> are not meant to be used directly.
> >
> > What about __doc__, __name__ and __slots__, to mention just a few?
> Excellent examples of "not meant to be used directly".

We obviously have different ideas about what that means, because I agree 
with everything you say but disagree with the conclusion. The idiom "if 
__name__ == '__main__'" is very common; and I frequently have scripts 
that "print __doc__" if given a --help command line option. And as you 
say, __slots__ is meant to be bound directly.

> > I believe that __import__() is the recommended way to import a
> > module known only at runtime. The docs also don't seem to agree 
> > with your assertion that __import__ is not to be touched. On the
> > contrary:
> >
> > "The function is invoked by the import statement. It mainly exists
> > so that you can replace it with another function that has a
> > compatible interface..."
> > http://docs.python.org/library/functions.html
> Yes, that documentation predates the current generation of import
> hooks which almost remove the need for such trickery.

Should this be reported as a documentation bug? Given the new import 
hooks, would it be fair to say that the main reason for __import__ is 
to use it to import a module whose name is only known at runtime?


More information about the Python-Dev mailing list