If I create a module named 'json.py' with the following contents:
#! python
import json as _json
JSONDecoder = _json.JSONDecoder
..shouldn't the 'import json as _json' statement perform an absolute import, and therefore provide the python standard-lib JSON module?
..instead, if I execute or import this module, I get:
$ python --version
Python 3.4.0
$ python relative_import/json.py
Traceback (most recent call last):
File "relative_import/json.py", line 3, in
import json as _json
File "/home/silver/Projects/relative_import/json.py", line 6, in
JSONDecoder = _json.JSONDecoder
AttributeError: 'module' object has no attribute 'JSONDecoder'
$
..which shows that 'json' is importing itself (a relative import). ..I imagine I'm missing something -- python's import system has always made natural and intuitive sense to me, but in this case I'm lost.
Edit: I'm using python 3.4
Edit: For anyone interested, this is what occurred: I have a package which includes a module called 'json', which replaces the system 'json'. This is fine (IMO), however, I also started a script that was in the same package folder (temporarily) but not meant to ultimately be a part of the same module. Thus, the following occurred:
- I run my script, packagename/foo.py
- python adds packagename folder to sys.path
- foo.py imports packagename.json
- packagename.json imports json (which would normally be the system json)
- first entry on sys.path is the packagename folder, and 'json' is imported from there
- my json.py continues loading after the import, and runs into errors (because it's dealing with itself, not the system json module)
Solution: Move the script to my package's 'bin' folder, or, if I want it to be a part of the package proper, use python -m packagename.foo
Thank you, @Martijn Pieters.