mjandrews
mjandrews

Reputation: 2464

controlling order of imports in python without changing sys.path

I am creating a personal utilities library like so

utils/
    __init__.py
    os.py
    sys.py
    string.py
    collections.py

I'm deliberately choosing those names.

I hit a problem if, within any of these modules I want to import the standard libary modules with the same names. For example, in my collections.py, I want to do

import collections 

where I want this to be the standard library collections. The trouble is that this imports itself, i.e. utils.collections and e.g.

   import string

will import utils.string, etc.

Is there any way around this problem? Presumably modifying sys.path is the recommended solution in situations like this. However, this would require, for each module in utils that I first do a

   import sys 

and that will import utils.sys and not the sys that I need. So I'm stuck again.

Upvotes: 1

Views: 141

Answers (1)

Justin O Barber
Justin O Barber

Reputation: 11591

The best solution would be to prevent these name collisions in the first place. But since you are probably past that point (or simply must use these names for other reasons), you might have to consider using Python 3.x's absolute_import instead:

from __future__ import absolute_import
import collections  # imports collections that is on sys.path
from . import collections as utils_collections  # now imports utils.collections

By default, Python 2.x will search your package before searching sys.path. Unfortunately, in your situation there is no way around this except the route I illustrate above.

Python 3.x, on the other hand, will by default search the absolute directories in sys.path unless preceded by a leading dot.

Upvotes: 1

Related Questions