0

Is it possible to import module within a python lambda function? For example, i have a lambda function which requires to import math

import math
is_na_yes_no = lambda x: 'Yes' if math.isnan(x) else 'No'

How can I include the import math statement within the lambda function?

To clarify, I have a scenario that need to put some lambda functions in a config file and evaluate the function in some other python files, exmample:

{
  "is_na_yes_no" = "lambda x: 'Yes' if math.isnan(x) else 'No'"
}

In this case, the python file that evaluating those lambda functions need to all modules required.

11
  • 7
    Why would you want to do that? Commented Oct 4, 2019 at 9:30
  • What is the XY Problem? Commented Oct 4, 2019 at 9:32
  • so for each iterable you want to import again and again, this is bad Commented Oct 4, 2019 at 9:32
  • 2
    Yay codegolfing.. lambda x:'Yes'if __import__('math').isnan(x)else'No' Commented Oct 4, 2019 at 9:47
  • 2
    Why do they have to be lambda functions? Why can't they be real functions? Commented Oct 4, 2019 at 9:50

1 Answer 1

3

Thanks @L3viathan for the answer.

Here is same thing without having to import math in the module.

is_na_yes_no = lambda x: 'Yes' if __import__('math').isnan(x) else 'No'

It highlights the flexibility of python -- __import__ feature can be used in lambda functions instead of having them written out before hand.

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

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.