RickyA RickyA - 2 years ago 146
Python Question

Force Python namespace import

Is there a way to force an import to use the Python namespace instead of the local one?
I am "overriding" the json module, so in my projects I always use the correct encoder and parameters:

project/foo/json.py: (mark this filename)

import json as pyjson

class ComplexEncoder(pyjson.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
if type(obj) == file:
return "filestream"
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))

def dumps(data):
return pyjson.dumps(data, cls=ComplexEncoder, check_circular=False, separators=(',', ':'), ensure_ascii=False)

def loads(data):
return pyjson.loads(data)

When I import this file I get the dreaded
AttributeError: 'module' object has no attribute 'JSONEncoder'
confirms my suspicion that
import json as pyjson
imports its own file instead of the python json module.

Is there a way to force the import of python json's module?

Answer Source

If your "json" module is inside a package, then this will fix it:

from __future__ import absolute_import

With that __future__ statement, imports will be absolute be default - i.e. it will only look for a top-level module or file called json.

If you need to import your local one, you can either do import foo.json, or you can explictly ask for a relative import using from . import json or from .json import dumps.

(I am assuming you're using Python 2).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download