2

Python 2.7 comes with json library included. In my PYTHONPATH I include third party sources and one of them is also called json. The result ending up with loaded the wrong json library. What would be a good practice to handle and avoid situations like above? Is there a way to instruct Python to explicitly load the native library in this fashion from ? import json.

1
  • I suggest you try and modify your code and leave Python the way it is. You will have to modify every new module you include to account for your code. Commented Dec 2, 2011 at 17:59

2 Answers 2

2

You could try

from path import json as anotherjson

This way the namespace conflict can be removed.

Also you can see the discussions about relative/absolute import.

It says :

In Python 2.5, you can switch import‘s behaviour to absolute imports using a from future import absolute_import directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import string will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible.

from __future__ import absolute_import
# from standard path
import json as _json 
# from a package
from pkg import json as pkgjson

The other technique is to use the imp module

import imp
json = imp.load_source('json', '/path/to/json.py')
Sign up to request clarification or add additional context in comments.

Comments

2

There really is no good way to have multiple modules with the same name on PYTHONPATH[docs], this means that you should probably move the third party json module to an alternate location that is not on PYTHONPATH, and then import it using some other method.

The easiest way to do this is to move the third party json module into a subdirectory of the location it is already in, and then make that subdirectory a module by adding __init__.py to it.

If you named this new directory 'thirdparty', you could then import your third party json module using from thirdparty import json, and import json would always import Python's json module.

Alternatively, you could rename the module to something that does not conflict.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.