44

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 }

So it iterates over the set of "libs" and "require" (import) each one of them. Now I'm writing a Python script and I would like to do something like that. Is there a way to, or do I need to write "import" for all of them.

The straight-forward "traduction" would be something like the following code. Anyway, since Python does not import libs named as strings, it does not work.

requirements = [lib1, lib2, lib3, lib4, lib5]
for lib in requirements:
    import lib
starball
  • 20,030
  • 7
  • 43
  • 238
Eduardo
  • 443
  • 1
  • 4
  • 5
  • 1
    Python actually does have a built-in function [`__import__`](http://docs.python.org/library/functions.html#__import__) which you can use to import a module named in a string. But it's meant to be called from the implementation of the `import` statement, not from user code. It certainly wouldn't be the proper solution in this case. – David Z Jul 15 '10 at 22:38
  • Oh! Really thanks for all the answers. Very good all of them. – Eduardo Jul 15 '10 at 22:59

8 Answers8

73

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Brian
  • 116,865
  • 28
  • 107
  • 112
  • 1
    Please note that the first code snippet defies Pep 8's recommendations https://www.python.org/dev/peps/pep-0008/#imports – Minion Jim Jul 11 '19 at 10:20
32

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
John Howard
  • 61,037
  • 23
  • 50
  • 66
16

if you want multi-line:

from englishapps.multiple.mainfile import (
    create_multiple_,
    get_data_for_multiple
)
Edgar Manukyan
  • 1,153
  • 10
  • 21
10

import lib1, lib2, lib3, lib4, lib5

ykaganovich
  • 14,736
  • 8
  • 59
  • 96
5

I just learned from a coworker today that, according to the PEP 8 Style Guide, imports in Python should actually be written on separate lines:

import os
import sys

The style guide calls import sys, os wrong.

Dan Swain
  • 2,910
  • 1
  • 16
  • 36
4

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)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
txwikinger
  • 3,006
  • 1
  • 25
  • 33
3

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)>
MSeifert
  • 145,886
  • 38
  • 333
  • 352
-1

Yes, you can import a list of libraries from a txt file in Python. It is very simple.

Example: If we have a text file libraries.txt content:

import numpy as np
import matplotlib.pyplot as plt
import rasterio

Here is some sample code that demonstrates how to import a list of libraries from a txt file containing import statements:

with open('libraries.txt', 'r') as f:
    lines = f.readlines()

for line in lines:
    exec(line)
Thai Tran
  • 1
  • 1