Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] 5 Easy Ways to List Imported Modules in Python

#1
5 Easy Ways to List Imported Modules in Python

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;341830&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">In this article, you’ll learn how to display the imported modules in Python. </p>
<p>As a Python Coder, you will encounter times when you need to view a list of all imported modules possessing a <strong>global </strong>or <strong>local </strong>scope. This article answers the question below.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write Python code to display the imported modules?</em></p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>
<ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio">
<li><strong>Method 1</strong>: Use <code><a rel="noreferrer noopener" href="https://blog.finxter.com/a-guide-of-all-pip-commands/" data-type="URL" data-id="https://blog.finxter.com/a-guide-of-all-pip-commands/" target="_blank">pip</a> freeze</code></li>
<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a></li>
<li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dir-a-simple-guide-with-video/" data-type="URL" data-id="https://blog.finxter.com/python-dir-a-simple-guide-with-video/" target="_blank"><code>dir()</code></a></li>
<li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/inspect.html" data-type="URL" data-id="https://docs.python.org/3/library/inspect.html" target="_blank"><code>inspect.getmember()</code></a> and a <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">Lambda</a></li>
<li><strong>Bonus</strong>: Count Number of Imported Modules</li>
</ul>
<hr class="wp-block-separator" />
<h2>Method 1: Use pip freeze</h2>
<p class="has-global-color-8-background-color has-background">This method displays a list of all imported <strong>global</strong> module names and versions <strong>sorted</strong>, by default, in alphabetical order.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip freeze</pre>
<p>Navigate to the terminal window from an IDE and enter the above command. Then, hit the &lt;<code>Enter</code>&gt; key to execute. The output is sent to the terminal.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />&nbsp;<strong>Note</strong>: Your prompt may be different from the example shown above.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="PIP Commands – A Simple Guide" width="780" height="585" src="https://www.youtube.com/embed/vtGZNLMi4yU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output (snippet)</strong></p>
<p>Your imported <strong>global </strong>module names and versions may differ from that shown below. </p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>absl-py==1.0.0<br />anyio==3.5.0<br />argon2-cffi==21.3.0<br />argon2-cffi-bindings==21.2.0<br />arrow==1.2.2<br />asttokens==2.0.5<br />astunparse==1.6.3<br />attrs==18.2.0<br />Babel==2.10.1<br />backcall==0.2.0<br />beautifulsoup4==4.10.0<br /><strong>...</strong><br />zope.interface==5.4.0]</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator" />
<h2>Method 2: Use List Comprehension</h2>
<p class="has-global-color-8-background-color has-background">This example uses the <code>sys</code> library with <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprenehsion</a> to return all imported <strong>local</strong> module names, by default, in an unsorted list.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2-3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import sys
results = [m.__name__ for m in sys.modules.values() if m]
results = sorted(results)
print(results)</pre>
<p>This code loops through <a rel="noreferrer noopener" href="https://docs.python.org/3/library/sys.html" data-type="URL" data-id="https://docs.python.org/3/library/sys.html" target="_blank"><code>sys.modules.values()</code></a> using <code>__name__</code> (aka a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dunder-methods-cheat-sheet/" data-type="URL" data-id="https://blog.finxter.com/python-dunder-methods-cheat-sheet/" target="_blank">dunder</a>) and determines if the item is a <strong>locally </strong>scoped module. If so, the module name saves to <code>results</code>. </p>
<p>This code sorts the <code>results</code> variable and saves it back to itself for readability. These <code>results</code> are output to the terminal in <a href="https://blog.finxter.com/python-lists/">list</a> format.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Single and Double Underscore in Python [&quot;_&quot; vs &quot;__&quot;]" width="780" height="439" src="https://www.youtube.com/embed/azb6JSp7RJI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output (snippet)</strong></p>
<p>Your imported <strong>local</strong> module names may differ from that shown below.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['<strong>main</strong>', '_abc', '_codecs', '_collections', '_distutils_hack', '_functools', '_imp', '_operator', '_signal', '_sitebuiltins', '_stat', '_thread', '_warnings', '_weakref', 'abc',...'zope']</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator" />
<h2>Method 3: Use dir()</h2>
<p class="has-global-color-8-background-color has-background">This example uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dir-a-simple-guide-with-video/" data-type="URL" data-id="https://blog.finxter.com/python-dir-a-simple-guide-with-video/" target="_blank"><code>dir()</code></a> function to return all <strong>local </strong>module names in a <strong>sorted</strong> <a href="https://blog.finxter.com/python-lists/">list</a> format. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">modules = dir()
print(modules)</pre>
<p>The output below confirms this script displays only the names that apply to our <strong>local </strong>scope.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python dir() — A Simple Guide with Video" width="780" height="439" src="https://www.youtube.com/embed/DZyICkSIPRI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output (snippet)</strong></p>
<p>Your imported <strong>local</strong> module names may differ from that shown below.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['annotations', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec']</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator" />
<h2>Method 4: Use <code>inspect.getmember()</code> and a Lambda</h2>
<p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://docs.python.org/3/library/inspect.html" data-type="URL" data-id="https://docs.python.org/3/library/inspect.html" target="_blank"><code>inspect.getmember()</code></a> and a <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">Lambda</a> to return the imported <strong>local </strong>modules in a <strong>sorted </strong>format.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import inspect
import os
m = inspect.getmembers(os)
res = filter(lambda x: inspect.ismodule(x[1]), m) for r in res: print®</pre>
<p>This code returns the names of the imported <strong>local </strong>modules and their location on the system as an iterable object. A <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> the loop is used to iterate through this and output one/line.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Let's Play Finxter - The Lambda Function in Python" width="780" height="439" src="https://www.youtube.com/embed/kBg4n52XoUQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output</strong></p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>('abc', &lt;module 'abc' from 'C:\\mypythoninstall\\lib\\abc.py'&gtWink<br />('path', &lt;module 'ntpath' from 'C:\\mypythoninstall\\lib\\ntpath.py'&gtWink<br />('st', &lt;module 'stat' from 'C:\\mypythoninstall\\lib\\stat.py'&gtWink<br />('sys', &lt;module 'sys' from 'C:\\mypythoninstall\\lib\\sys.py'&gtWink</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator" />
<h2>Bonus: Count Modules</h2>
<p class="has-global-color-8-background-color has-background">If you want to determine the total number of imported modules, use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dir-a-simple-guide-with-video/" data-type="URL" data-id="https://blog.finxter.com/python-dir-a-simple-guide-with-video/" target="_blank"><code>dir()</code></a> and <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-len/" data-type="URL" data-id="https://blog.finxter.com/python-len/" target="_blank">len()</a></code> functions.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">count = dir()
print(len(count))</pre>
<p>This code references the imported <strong>local </strong>modules and uses <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-len/" data-type="URL" data-id="https://blog.finxter.com/python-len/" target="_blank">len()</a></code> to determine how many are imported. The output is sent to the terminal.</p>
<p><strong>Output</strong></p>
<p>Your <code>count</code> may differ from the output below.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td>11</td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator" />
<p> <span style="color: var(--contrast);font-size: 44px;font-weight: bold">Summary</span> </p>
<p>These four (4) methods to list imported modules should give you enough information to select the best one for your coding requirements.</p>
<p>Good Luck &amp; Happy Coding!</p>
<hr class="wp-block-separator" />
</div>


https://www.sickgaming.net/blog/2022/05/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016