Why does this absolute import not work in Python?

I have two Python 2.6 file /code/x/X.py:

import imp
print 'running'
logging = imp.load_source('logging', '/code/y/logging.py')

... and /code/y/logging.py:

from __future__ import absolute_import
import logging as _logging

import sys, os
print sys.path
print os.getcwd()
print _logging

Performing X.pyprint:

running
['/code/x', '/usr/lib/pymodules/python2.6', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/plat-linux2', '/usr/local/lib/python2.6/dist-packages']
/code/x
<module 'logging' from '/code/y/logging.py'>

Why is it not from __future__ import absolute_importforcing imports import loggingimport, and not local? In other words, why can't I see the system registration module?

+3
source share
1 answer

The problem is the team imp.load_source. The first argument is the name in which it registers the module, and subsequent imports will first look in the loaded modules before searching for the path. Changing a string to use a different name, for example:

logging = imp.load_source('logx', '/code/y/logging.py')

... fixes the problem.

+3
source

Source: https://habr.com/ru/post/1789276/


All Articles