Popular recipes by roopeshv http://code.activestate.com/recipes/users/4174204/2010-06-16T23:17:20-07:00ActiveState Code RecipesImport modules in lambda functions (Python) 2010-06-16T20:13:15-07:00roopeshvhttp://code.activestate.com/recipes/users/4174204/http://code.activestate.com/recipes/577269-import-modules-in-lambda-functions/ <p style="color: grey"> Python recipe 577269 by <a href="/recipes/users/4174204/">roopeshv</a> . </p> <p>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.</p> <p>Instead of having the following function, which joins the paths</p> <pre class="prettyprint"><code>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) &gt;&gt;&gt; relative_to_current('Desktop') '/home/user/Desktop' # on linux 'C:\\Users\\Desktop' </code></pre> <p>Here is same thing without having to import os in the module.</p> dealing with directory paths with ~ (Python) 2010-06-16T23:17:20-07:00roopeshvhttp://code.activestate.com/recipes/users/4174204/http://code.activestate.com/recipes/577270-dealing-with-directory-paths-with/ <p style="color: grey"> Python recipe 577270 by <a href="/recipes/users/4174204/">roopeshv</a> (<a href="/recipes/tags/directory/">directory</a>, <a href="/recipes/tags/expanding/">expanding</a>, <a href="/recipes/tags/paths/">paths</a>). Revision 2. </p> <p>Dealing with directory paths which start with <code>~</code> which are passed as paramaters, to <code>os</code> module functions.</p> <p>Here is what I think python doesn't do for me:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; import os # suppose my home = curdir = /home/rv &gt;&gt;&gt; os.path.abspath('.') '/home/rv' </code></pre> <p>Now if I want to go to folder <code>/home/rv/test</code> if there is no folder by name /home/rv/~/test/</p> <pre class="prettyprint"><code># This is what happens by default. &gt;&gt;&gt; os.path.abspath('~/test') '/home/rv/~/test' &gt;&gt;&gt; os.chdir('/home/rv/some/dir') # doesn't matter if the resulting path exists or not. &gt;&gt;&gt; os.path.abspath('~/test') 'home/rv/some/dir/~/test' </code></pre> <p>This would be more sensible I guess:</p> <pre class="prettyprint"><code># if /home/rv/~/test doesn't exist &gt;&gt;&gt; os.path.abspath('~/test') '/home/rv/test' </code></pre>