Python built-in function __import__

Source: Internet
Author: User

We know that the import statement is for importing external modules, and of course from...import ... Yes, but actually import actually works using the BUILTIN function __import__.
In some programs, we can dynamically call the function, if we know the name of the module (string), we can easily use dynamic invocation.

import glob,os    modules = []   for module_file in glob.glob ("*-plugin.py"):       try :          module_name,ext = os.path.splitext ( Os.path.basename (module_file))          module = __ import__ (module_name)          modules.append (module)        except importerror:         pass   #ignore  broken modules       #say  hello to all  modules      for module in modules:          module.hello () 

Use the __import__ function to get a specific function

def getfunctionbyname (module_name,function_name): module = __import__ (module_name) return GetAttr (module,functio N_name)

You can also use this function to implement deferred module import

class lazyimport:         def __init__ (Self,module_name):             self.module_name = module_name             self.module = none        def __getattr__ (Self, Name):             if self.module is  None:                self.module = __import__ (Self.module_name)              return getattr (Self.module,name)   string = lazyimport ("string")   print string.lowercase 


This article is from the "Lu Yaliang" blog, make sure to keep this source http://luyaliang.blog.51cto.com/3448477/1767085

Python built-in function __import__

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.