import mysteries
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Fri Jun 22 02:30:46 EDT 2007
On Thu, 21 Jun 2007 16:03:42 -0400, David Abrahams wrote:
> I'm pretty comfortable with Python, but recently I'm constantly finding
> mysterious issues with import. For example, looking at
>
> http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py
>
> the examples use the symbol 'HTML' but it's not defined locally, it's
> not explicitly imported, and there's no import *. Yet doctest will test
> this module and it passes with flying colors. It turns out HTML is
> defined in genshi.input. How do I know that? I grepped for it. How
> does it become available to this module?
There are ways to bypass the import system. The most obvious would be to
write directly to globals.
>>> spanish_inquisition
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spanish_inquisition' is not defined
>>> globals()['spanish_inquisition'] = "NOBODY expects the Spanish
Inquisition!!!"
>>> spanish_inquisition
'NOBODY expects the Spanish Inquisition!!!'
> Another example: I was recently working on some code that did an import
> from inside a class method. That import was failing. I moved the
> import to the top of the file (at module scope) and it succeeded. I'm
> fairly sure that nobody was monkeying around with sys.path in that case.
> Can anyone think of a likely explanation?
If it was a "from MODULE import *" then it will not work if it is nested
in a function or class. That's by design.
--
Steven.
More information about the Python-list
mailing list