How to do multiple imports in Python?

前端 未结 5 2215
我寻月下人不归
我寻月下人不归 2020-12-05 04:48

In Ruby, instead of repeating the \"require\" (the \"import\" in Python) word lots of times, I do

%w{lib1 lib2 lib3 lib4 lib5}.each { |x| require x }
         


        
5条回答
  •  悲哀的现实
    2020-12-05 05:00

    You can use __import__ if you have a list of strings that represent modules, but it's probably cleaner if you follow the hint in the documentation and use importlib.import_module directly:

    import importlib
    requirements = [lib1, lib2, lib3, lib4, lib5]
    imported_libs = {lib: importlib.import_module(lib) for lib in requirements}
    

    You don't have the imported libraries as variables available this way but you could access them through the imported_libs dictionary:

    >>> requirements = ['sys', 'itertools', 'collections', 'pickle']
    >>> imported_libs = {lib: importlib.import_module(lib) for lib in requirements}
    >>> imported_libs
    {'collections': ,
     'itertools': ,
     'pickle': ,
     'sys': }
    
    >>> imported_libs['sys'].hexversion
    50660592
    

    You could also update your globals and then use them like they were imported "normally":

    >>> globals().update(imported_libs)
    >>> sys
    
    

提交回复
热议问题