How did the import expression detect this module?

Given the following directory structure:

here/
├── app
│   ├── __init__.py
│   ├── json.py
│   └── example.py
└── my_script.py

__init__.pyand json.py- empty files.

Content my_script.py:

from app import example

Content example.py

import importlib, imp, sys, os

# ensures '' is not in sys.path
sys.path = [p for p in sys.path if p]

# ensures PYTHONPATH, if any, is not over-reaching
os.environ.pop('PYTHONPATH', None)

# ensures we do not see json.py in the cwd
assert not os.path.isfile('json.py')

print '1: ', imp.find_module('json')
print '2: ', __import__('json')
print '3: ', importlib.import_module('json')

import json
json.loads

Now from the directory heredo:

python ./my_script.py

You will see that methods 1, 2, 3, all find the version of the base module library json.

However, the actual import statement still manages to somehow capture the empty file json.py( AttributeError: 'module' object has no attribute 'loads').

I realized that the batch version of json here should be available only for the namespace, i.e. from app import jsonbut the namespace does not work here.

On python3, I cannot reproduce the problem. I also noticed that if we put from __future__ import absolute_importin a file example.py, the problem just disappears.

?

: , import json, json, sys.modules . , python , ?

+4
1

. Python 2.x , "" .

python 2. . .

, from __future__ import absolute_import, Python 2.5, PEP 328. Python 3. ( ) , ( ), (.. .. , ... ..)

+2

All Articles