3

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?

6
  • 4
    You can't use an import statement inside a lambda expression. Commented Feb 24, 2020 at 15:59
  • 2
    Why do you want to use a lambda? Just use a standard function def Commented Feb 24, 2020 at 16:01
  • I want to decrease the size of code that is the only reason behind using lambda Commented Feb 24, 2020 at 16:03
  • 9
    That is the worst imaginable reason to use a lambda. Commented Feb 24, 2020 at 16:04
  • 5
    No, lambda expressions are used when you don't otherwise need a name for the function being created. The "size of the code" has nothing to do with it. Commented Feb 24, 2020 at 16:11

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.