How to import a python module inside lambda?

Viewed 2066

For suppose depending upon the variable I want to import some classes, create its object and return it. for example :

if x=='SomeThing':
  import something
  object = something's object
else:
  import nothing
  object = nothing's object
object.function()

I want to do the above using the lambda how can I do this?

2 Answers

You can use magic __import__:

importer = lambda x: (__import__("pandas").DataFrame if x == 0 
                      else __import__('numpy').arange)

NOTE: This is extremely ugly, and not at all recommended, unless you absolutely need to do it.

It is rarely an issue to simply import both modules unconditionally, and select which module to actually use later.

import something
import nothing

(something if x == 'SomeThing' else nothing).object.function()

If you do need to perform conditional imports, import one or the other, but using the same name.

if x == 'SomeThing':
    import something as thingmodule
else:
    import nothing as thingmodule

thingmodule.object.function()
Related