How to do multiple imports in Python?

前端 未结 5 2190
我寻月下人不归
我寻月下人不归 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': <module 'collections' from 'lib\\collections\\__init__.py'>,
     'itertools': <module 'itertools' (built-in)>,
     'pickle': <module 'pickle' from 'lib\\pickle.py'>,
     'sys': <module 'sys' (built-in)>}
    
    >>> 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
    <module 'sys' (built-in)>
    
    0 讨论(0)
  • 2020-12-05 05:07

    For known module, just separate them by commas:

    import lib1, lib2, lib3, lib4, lib5
    

    If you really need to programmatically import based on dynamic variables, a literal translation of your ruby would be:

    modnames = "lib1 lib2 lib3 lib4 lib5".split()
    for lib in modnames:
        globals()[lib] = __import__(lib)
    

    Though there's no need for this in your example.

    0 讨论(0)
  • 2020-12-05 05:14

    import lib1, lib2, lib3, lib4, lib5

    0 讨论(0)
  • 2020-12-05 05:17

    You can import from a string which contains your module name by using the __import__ function.

    requirements = [lib1, lib2, lib3, lib4, lib5]
    for lib in requirements:
        x = __import__(lib)
    
    0 讨论(0)
  • 2020-12-05 05:23

    Try this:

    import lib1, lib2, lib3, lib4, lib5
    

    You can also change the name they are imported under in this way, like so:

    import lib1 as l1, lib2 as l2, lib3, lib4 as l4, lib5
    
    0 讨论(0)
提交回复
热议问题