I am not sure how many know that we can import modules inside lambda functions. So I am writing this to make the feature standout.
Instead of having the following function, which joins the paths
import os
relative_to_current = lambda *x: os.path.join(os.path.dirname(__file__), *x)
# current directory is suppose /home/user/ (on linux) OR C:\Users (on Windows)
>>> relative_to_current('Desktop')
'/home/user/Desktop' # on linux
'C:\\Users\\Desktop'
Here is same thing without having to import os in the module.
1 | relative_to_current = lambda *x: __import__('os').path.join(__import__('os').path.dirname(__file__), *x)
|
This is just to highlight the __import__ feature which can be used in lambda functions instead of having them written out on before hand.
Cool. Interesting thought.
I knew about the function...I just hadn't thought about it this way before.
Thanks!
yean ... __import__ is also virtually a callable that works like others. but i guess __import__ is more used to customize the import procedure. but ur demo just shows again that python is really an interesting language.