For instance, I want to make a sql alchemy plugin for another project. And I want to name that module sqlalchemy.py. The problem with this is that it prevents me from importing sqlalchemy:
#sqlalchemy.py
import sqlalchemy
This will make the module import itself. I’ve tried this, but it doesn’t seem to work:
import sys
#Remove the current directory from the front of sys.path
if not sys.path[0]:
sys.path.pop(0)
import sqlalchemy
Any suggestions?
Edit: as the OP has now mentioned that the issue is one of relative import being preferred to absolute, the simplest solution for the OP’s specific problem is to add at the start of the module
from __future__ import absolute_importwhich changes that “preference”/ordering.The following still applies to the ticklish issue of two clashing absolute imports (which doesn’t appear to be what the OP is currently facing…):
Once you’ve imported a module named
x, that module’s recorded insys.modules['x']— changing sys.path as you’re doing won’t alter sys.modules. You’ll also need to alter sys.modules directly.E.g., consider:
(running again will use and show the .pyc files instead of the .py ones of course).
Not the cleanest approach, and of course this way the original foo module is, inevitably, not accessible from the outside any more (since its sys.modules entry has been displaced), but you could play further fragile tricks as needed (stash
sys.modules["foo"]somewhere before deleting it, after you import the other foo put that module somewhere else and reinstate the originalsys.modules["foo"]— etc, etc), depending on your exact needs. (Of course, avoiding the name clashes in the first place would almost invariably be simpler than waltzing all around them in this way;-).