Python dynamic import module

Source: Internet
Author: User

Python dynamic import module

If the imported module does not exist, the Python interpreter reports the ImportError error:

>>> import somethingTraceback (most recent call last):  File "
 
  ", line 1, in 
  
   ImportError: No module named something
  
 

Sometimes, two different modules provide the same functions, suchStringIOAndCStringIOAll provide the StringIO function.

This is because Python is a dynamic language and interpreted and executed, so Python code runs slowly.

To speed up the running of Python code, the simplest method is to rewrite some key functions in C language, which can greatly improve the execution speed.

With the same function, StringIO is written in pure Python code, while some cStringIO functions are written in C, so cStringIO runs faster.

Using ImportError errors, we often use Python to dynamically import modules:

try:    from cStringIO import StringIOexcept ImportError:    from StringIO import StringIO

The above code first tries to import from cStringIO. If it fails (for example, cStringIO is not installed), then try to import from StringIO. In this way, if the cStringIO module exists, we will get a faster running speed. If the cStringIO module does not exist, the running speed of at most code will be slow, but it will not affect normal code execution.

TryIs used to capture errors and executeExceptStatement.

Task

Using import... as..., you can also dynamically import modules with different names.

Python 2.6/2.7ProvidedJsonModule, but Python 2.5 and earlier versions do not have a json module, but you can installSimplejsonThe two modules provide the same function signature and function.

Try to write and importJsonThe module code can run properly in Python 2.5/2.6/2.7.

? No, what should I do?

Try to import json first. If it fails, try to import simplejson as json

Reference code:

try:    import jsonexcept ImportError:    import simplejson as jsonprint json.dumps({'python':2.7})

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.