Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a module based on installed python version?

Tags:

python

json

My module currently imports the json module, which is only available in 2.6. I'd like to make a check against the python version to import simplejson, which can be built for 2.5 (and is the module adopted in 2.6 anyway). Something like:

if __version__ 2.5:
    import simplejson as json
else:
    import json

What's the best way to approach this?

like image 421
Wells Avatar asked Dec 09 '09 16:12

Wells


People also ask

How do you dynamically import a module using a function Python?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module.

Can you manually import a module in Python?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.


1 Answers

try:
    import simplejson as json
except ImportError:
    import json

of course, it doesn't work around cases when in python-2.5 you don't have simplejson installed, the same as your example.

like image 118
SilentGhost Avatar answered Oct 10 '22 19:10

SilentGhost