__all__ in Python and What It Does

<p>Let&rsquo;s say we have 2 Python scripts.</p> <ul> <li>main.py &mdash; the script that we want to run</li> <li>helper.py &mdash; main.py imports stuff from this script</li> <li>these 2 scripts are in the same folder</li> </ul> <pre> # helper.py a = 4 b = 5 c = 6 def test(): print(&#39;test&#39;)</pre> <pre> # main.py from helper import * print(a, b, c) # 4 5 6 test() # test</pre> <ul> <li>In main.py, the line&nbsp;<code>from helper import *</code>&nbsp;means that&nbsp;<em>everything&nbsp;</em>inside helper.py is imported into main.py</li> <li>this is why we can use&nbsp;<code>a</code>&nbsp;<code>b</code>&nbsp;<code>c</code>&nbsp;and&nbsp;<code>test</code>&nbsp;in main.py</li> </ul> <h1>What if I want to do a partial import?</h1> <p>Let&rsquo;s say instead of import&nbsp;<code>a</code>&nbsp;<code>b</code>&nbsp;<code>c</code>&nbsp;and&nbsp;<code>test</code>, I only wish to import&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>&nbsp;only. In main.py, we can change up the&nbsp;<code>from helper import *</code>&nbsp;statement.</p> <pre> # helper.py a = 4 b = 5 c = 6 def test(): print(&#39;test&#39;)</pre> <pre> # main.py from helper import a, b print(a, b) # 4 5 # attempting to use c or test will cause error</pre> <ul> <li>the statement&nbsp;<code>from helper import a, b</code>&nbsp;imports ONLY&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>&nbsp;from helper.py &mdash;&nbsp;<code>c</code>&nbsp;and&nbsp;<code>test</code>&nbsp;are not imported.</li> <li>this is how we can partial import</li> </ul> <p><a href="https://levelup.gitconnected.com/all-in-python-and-what-it-does-fb08a9f0a884">Click Here</a>&nbsp;</p>
Tags: Python Scripts