[Tutor] force imports from site-packages?

Steven D'Aprano steve at pearwood.info
Fri Oct 7 04:54:48 CEST 2011

Alex Hall wrote:
> Hi all,
> I have managed to get a couple of packages in site-packages which
> share names with some folders in the same directory as a program, or
> at least a subdir somewhere below has the same name. Is there a way to
> force my script to look in lib/site-packages before the script's
> folder? I can't rename these folders since Git will get confused if I
> do.
> In other words, I have a package called LRSignature installed, but in
> a subdir of my script's directory is another LRSignature folder which
> is not an actual Python package. Python sees this non-package folder

It shouldn't. Python doesn't look into nested folders unless you 
explicitly add them to the search path. Here's an example:

[steve at sylar ~]$ mkdir math
[steve at sylar ~]$ echo "print('spam')" > math/module.py
[steve at sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import math  # Can we still see the standard math module?
 >>> math.sin(1)
 >>> import module  # How about the other module?
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ImportError: No module named module

So as you can see, the math subdirectory and its content is ignored by 
Python because it isn't explicitly part of the search path. So I don't 
understand why you are seeing this problem unless you are cd'ing into 
the LRSignature folder first.

> first and so, quite rightly, throws an exception that the class of the
> package I want, LRSignature.Sign, does not exist. It exists in the
> site-packages copy, but Python won't overlook the nearer copy. How do
> I make it do this? Thanks.

The *right* solution is to fix the name clash, which may or may not 
involve changing the name of something. But I can't tell what, since I 
don't understand why you are having this problem.

But if you can't fix the problem, you can cover it up by manipulating 
the import search path. It is exposed as sys.path, and it is just a list 
of places to look in the specific order given.


More information about the Tutor mailing list