简体   繁体   中英

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, ie utils.collections and eg

   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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM