Absolute imports in Python 2.4

  • Thread starter Steven D'Aprano
  • Start date
S

Steven D'Aprano

I have a package which includes a module which shadows a module in the
standard library. For example:

package
+-- __init__.py
+-- ham.py
+-- spam.py
+-- sys.py

Inside that package, I want to import the standard library sys. In other
words, I want an absolute import. In Python 2.7, absolute imports will be
the default, and "import sys" will import the standard library module. To
get to the package.sys module, I'll need "from . import sys".

In Python 2.5 and 2.6, relative imports are the default, and package.sys
will shadow the std lib version. I can say:

from __future__ import absolute_import

to use the Python 2.7 behaviour.

What can I do in Python 2.4 to get an absolute import?

I've read PEP 328 and googled, but haven't found any useful advice other
than "well don't do that then". Plenty of pages complaining about
relative imports, but I haven't found any work-arounds others than
renaming the offending module. Are there any other ways around this?

http://www.python.org/dev/peps/pep-0328/
 
G

Gabriel Genellina

En Mon, 01 Jun 2009 21:40:26 -0300, Steven D'Aprano
I have a package which includes a module which shadows a module in the
standard library. For example:

package
+-- __init__.py
+-- ham.py
+-- spam.py
+-- sys.py

Inside that package, I want to import the standard library sys. In other
words, I want an absolute import. [...]
What can I do in Python 2.4 to get an absolute import?

sys = __import__("sys", {})

The import statement uses the global namespace to determine which package
it is called on; if you pass an empty namespace, it cannot infer package
information.

Anyway, the best move would be to rename the offending module...
 
S

Steven D'Aprano

En Mon, 01 Jun 2009 21:40:26 -0300, Steven D'Aprano
I have a package which includes a module which shadows a module in the
standard library. For example:

package
+-- __init__.py
+-- ham.py
+-- spam.py
+-- sys.py

Inside that package, I want to import the standard library sys. In
other words, I want an absolute import. [...] What can I do in Python
2.4 to get an absolute import?

sys = __import__("sys", {})

The import statement uses the global namespace to determine which
package it is called on; if you pass an empty namespace, it cannot infer
package information.

Oh that's very cunning! Nice trick.

Anyway, the best move would be to rename the offending module...

I agree. But it's nice to know the work-around if I need it.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top