Python dynamic import module

Source: Internet
Author: User

The purpose is to implement the module that should be applied when switching from the configuration file to run. It is complicated to use C # because it is a static language, so to switch dynamically, we only need to use reflection. python is much easier, as long asCodeBefore dynamic import, you can achieve the goal.

Assume that there is a package named "mypackage", which contains three modules: md01.py, md02.py, and md03.py, which implement the same method.

Def getstr (): Return "from md01/ 2/3"

Among them, 123 vary with Moudle.

So how can we use it?

From XML. Dom import minidomif _ name __= = "_ main _": # assume that an xml configuration file reads the Moudle node xml = ''' <? XML version = "1.0"?> <Root> <Moudle> md03 </Moudle> </root> ''' P = minidom. parsestring (XML) mdname = P. getelementsbytagname ("Moudle") [0]. firstchild. data mymod =__ import _ ("mypackage. "+ mdname, fromlist = [" * "]) # fromlist is very important to print mymod. getstr ()

During the test, the only thing that is ignored is the fromlist parameter in _ import _. No module can be obtained and only the package can be obtained, the reason is that the names of modules that may participate in the import must be written in fromlist,

This is a very good design. If you have a huge package, but you only need a few modules to participate, you can write the several modules into it.

If the imported module is in your own package, the fromlist is empty or you can send this parameter.

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.