Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple imports in Python?

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 

Thanks in advance

like image 345
Eduardo Avatar asked Jul 15 '10 22:07

Eduardo


People also ask

Can you import multiple things in Python?

You can import multiple functions, variables, etc. from the same module at once by writing them separated by commas.

How can you import multiple?

Select File from computer, then in the bottom right, click Next or press Enter. Select One file, and click Next or press Enter. Select Multiple objects, and click Next or press Enter. Select the objects in your import file.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.


2 Answers

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.

like image 116
Brian Avatar answered Sep 23 '22 00:09

Brian


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 
like image 24
John Howard Avatar answered Sep 23 '22 00:09

John Howard