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.

henrywongkk
  • 1,840
  • 3
  • 17
  • 26
  • 7
    Why would you want to do that? – Aran-Fey Oct 04 '19 at 09:30
  • [What is the XY Problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Sayse Oct 04 '19 at 09:32
  • so for each iterable you want to import again and again, this is bad – sahasrara62 Oct 04 '19 at 09:32
  • @aran-fey i want to add flexibility to my code by putting some lambda functions in a config file, but issue is that the python file executing those lambda functions must know what modules to import – henrywongkk Oct 04 '19 at 09:33
  • @Sayse it is not a XY problem, but i have a scenario it does not work – henrywongkk Oct 04 '19 at 09:34
  • @prashantrana - No iterables involved here. OP, You don't need a lambda here at all, just define the function and import that to other modules that would use it. – Sayse Oct 04 '19 at 09:34
  • You may be able to use importlib [as seen here](https://stackoverflow.com/questions/8718885/import-module-from-string-variable/8719100) to create a lambda to import from a string, but id say its highly inadvisable to do so – Kevin Müller Oct 04 '19 at 09:36
  • 2
    Yay codegolfing.. `lambda x:'Yes'if __import__('math').isnan(x)else'No'` – L3viathan Oct 04 '19 at 09:47
  • 2
    Why do they have to be lambda functions? Why can't they be real functions? – Aran-Fey Oct 04 '19 at 09:50
  • @Aran-Fey because my code is storing the functions as string in a json file, which is user-configurable. please let me know if you have other suggestions – henrywongkk Oct 04 '19 at 09:56
  • You can call an extra function in your lambda which imports a module. – mortymacs Oct 04 '19 at 10:08

1 Answers1

2

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.

henrywongkk
  • 1,840
  • 3
  • 17
  • 26