Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 1 line
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.

2 comments

Sunjay Varma 13 years, 10 months ago  # | flag

Cool. Interesting thought.

I knew about the function...I just hadn't thought about it this way before.

Thanks!

Chaobin Tang (ε”θΆ…ζ–Œ) 13 years, 9 months ago  # | flag

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.

Created by roopeshv on Wed, 16 Jun 2010 (PSF)
Python recipes (4591)
roopeshv's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks