tylerl
tylerl

Reputation: 30857

python import ignoring local package

Note that doing this is not a good idea. It's confusing, error-prone, and typically completely unnecessary.

But for the sake of argument, say you have a local package that with the same name as a global package:

module/
   __init__.py
   os.py
   thisfile.py

inside thisfile.py, you could explicitly specify that you wanted to import your local version of os.py using one of the following:

from . import os
from .os import foo

But in fact, with python 2.x, local package resolution is the default. Just a simple import os would load the local os.py instead of the system package.

So how do I, inside thisfile.py import the system-level os package instead of the locally-defined alternative?

Upvotes: 2

Views: 1407

Answers (2)

mata
mata

Reputation: 69042

This behaviour is python2 specific. In python3, imports are absolute by default to fix exactly this kind of problem.

In python2.5+*, you can fix this behaviour using a future import:

from __future__ import absolute_import

After that, all imports will be absolute and to import a module which has the same name as a top level module you have to use the explicit relative import syntax.

See PEP 328 for further background.


*edit: in earlier python versions, the only option would be to modify sys.path in a way that the top level module is found first - which is actually a terrible solution.

Upvotes: 6

Wolph
Wolph

Reputation: 80031

You have it the other way around.

# Absolute import
import os

# Relative import
from . import os

Docs: http://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

In older Python (everything below 3.0) versions you have to enable it manually though, here is a list with all the __future__ features

For Python 2.5-2.x:

from __future__ import absolute_import

Upvotes: 1

Related Questions