<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Logesh on Medium]]></title>
        <description><![CDATA[Stories by Logesh on Medium]]></description>
        <link>https://medium.com/@LogeshSakthivel?source=rss-40271b79ac98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JMuZyuWZQkc8g6ioZYnmKA.jpeg</url>
            <title>Stories by Logesh on Medium</title>
            <link>https://medium.com/@LogeshSakthivel?source=rss-40271b79ac98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:21:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@LogeshSakthivel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Python Namespace Packages]]></title>
            <link>https://towardsdev.com/python-namespace-packages-985a8672e900?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/985a8672e900</guid>
            <category><![CDATA[python-packages]]></category>
            <category><![CDATA[regular-packages]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[namespace-package]]></category>
            <category><![CDATA[namespaces]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 14:31:35 GMT</pubDate>
            <atom:updated>2024-12-31T17:04:35.856Z</atom:updated>
            <content:encoded><![CDATA[<p>In Python we have packages to organize the modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wbKZDxXVGdSO4gyfbpDyw.png" /><figcaption>Python Packages</figcaption></figure><p>Two types of packages:</p><ol><li>Regular Package</li><li>Namespace Package</li></ol><h3>Regular Package</h3><p>A <strong>regular package</strong> is a directory that contains an __init__.py file. This file indicates that the directory should be treated as a package. The __init__.py file can be empty, but it is often used to initialize the package, define what is exposed to the outside, or run setup code when the package is imported.</p><pre>mypackage/<br>    __init__.py<br>    module1.py<br>    module2.py</pre><h3>Namespace Package</h3><p>A <strong>namespace package</strong> is a package-like structure that does not require an __init__.py file and can span multiple directories. It allows for distributed and flexible package creation, enabling different parts of the package to be split across various locations.</p><h4>Example:</h4><p>Imagine the namespace package mynamespace distributed across two directories:</p><p>Directory 1:</p><pre><strong>project1</strong>/mynamespace/<br>    module1.py</pre><p>Directory 2:</p><pre><strong>project2</strong>/mynamespace/<br>    module2.py</pre><p>Usage</p><pre>import mynamespace.module1<br>import mynamespace.module2</pre><p>Python will combine the two mynamespace directories into a single namespace package, making all modules accessible.</p><h4>Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*g78Kn1z12Q6UmhPp6U0RmQ.png" /></figure><h3>Namespace package example</h3><blockquote>We learnt that source code of the Namespace package can be spread across multiple directories. It helps the large project to be de-coupled based on the teams so that the components of the packages can be developed and distributed independently.</blockquote><blockquote>Ex: One repository( one team) can work on one component, the other team can work on another component of the same package but developed and distributed independently.</blockquote><p>Lets learn how the Namespace package helps in developing and distributing the package independently.</p><p>Assume we have one corporation(<em>log-corp</em>) that provides one big useful package. But that package’s subpackage/modules are diversified across different repos(directories) as different teams are working on it.</p><ul><li><strong>log_corp </strong>is the main package which has many sub-packages and modules that are developed across the teams and distributed independently.</li><li>The Versioning and package distribution will happen independently.</li><li>The only thing they share is the namespace. (All the sub-packages and modules will come under the main package <strong><em>log_corp</em></strong>)</li></ul><h4>Team 1(Repo 1)</h4><p>Using the src layout.</p><pre>LOG_CORP_COMP1/<br>├── src/<br>│   └── <strong>log_corp</strong>/<br>│       ├── sub_pkg1/<br>│       │   └── sub_module1.py<br>│       └── module1.py<br>├── pyproject.toml<br>└── README.md</pre><p><strong><em>module1.py</em></strong></p><pre>def func1():<br>    print(&#39;From log-corp module1&#39;)</pre><p><strong><em>sub_module1.py</em></strong></p><pre>def sub_func1():<br>    print(&#39;From log-corp submodule1&#39;)</pre><p><strong><em>pyproject.toml</em></strong></p><pre>[build-system]<br>requires = [&quot;setuptools&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;<br><br>[project]<br>name = &quot;log-corp1&quot;  # as if it appears in pypi<br>authors = [<br>    {name = &quot;Logesh&quot;, email = &quot;log@gmail.com&quot;},<br>]<br>description = &quot;My package description&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>license = {text = &quot;MIT License&quot;}<br>classifiers = [<br>    &quot;Programming Language :: Python :: 3&quot;,<br>]<br>version = &quot;1.0.1&quot;   # version 1.0.1</pre><h4>Build the package</h4><pre>PS C:\Users\L\Desktop\log_corp_comp1&gt; ls<br><br><br>    Directory: C:\Users\L\Desktop\log_corp_comp1<br><br><br>Mode                 LastWriteTime         Length Name<br>----                 -------------         ------ ----<br>d-----        12/28/2024  11:32 AM                src<br>-a----        12/28/2024  11:41 AM            387 pyproject.toml<br>-a----        12/28/2024  11:31 AM             34 README.md<br><br><br>PS C:\Users\L\Desktop\log_corp_comp1&gt; <strong>python -m build</strong><br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for sdist...<br>running egg_info<br>creating src\log_corp1.egg-info<br>writing src\log_corp1.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp1.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp1.egg-info\top_level.txt<br>writing manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>reading manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>* Building sdist...<br>running sdist<br>running egg_info<br>writing src\log_corp1.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp1.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp1.egg-info\top_level.txt<br>reading manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>running check<br>creating log_corp1-1.0.1<br>creating log_corp1-1.0.1\src\log_corp<br>creating log_corp1-1.0.1\src\log_corp1.egg-info<br>creating log_corp1-1.0.1\src\log_corp\sub_pkg1<br>copying files to log_corp1-1.0.1...<br>copying README.md -&gt; log_corp1-1.0.1<br>copying pyproject.toml -&gt; log_corp1-1.0.1<br>copying src\log_corp\module1.py -&gt; log_corp1-1.0.1\src\log_corp<br>copying src\log_corp1.egg-info\PKG-INFO -&gt; log_corp1-1.0.1\src\log_corp1.egg-info<br>copying src\log_corp1.egg-info\SOURCES.txt -&gt; log_corp1-1.0.1\src\log_corp1.egg-info<br>copying src\log_corp1.egg-info\dependency_links.txt -&gt; log_corp1-1.0.1\src\log_corp1.egg-info<br>copying src\log_corp1.egg-info\top_level.txt -&gt; log_corp1-1.0.1\src\log_corp1.egg-info<br>copying src\log_corp\sub_pkg1\sub_module1.py -&gt; log_corp1-1.0.1\src\log_corp\sub_pkg1<br>copying src\log_corp1.egg-info\SOURCES.txt -&gt; log_corp1-1.0.1\src\log_corp1.egg-info<br>Writing log_corp1-1.0.1\setup.cfg<br>Creating tar archive<br>removing &#39;log_corp1-1.0.1&#39; (and everything under it)<br>* Building wheel from sdist<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for wheel...<br>running egg_info<br>writing src\log_corp1.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp1.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp1.egg-info\top_level.txt<br>reading manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>* Building wheel...<br>running bdist_wheel<br>running build<br>running build_py<br>creating build\lib\log_corp<br>copying src\log_corp\module1.py -&gt; build\lib\log_corp<br>creating build\lib\log_corp\sub_pkg1<br>copying src\log_corp\sub_pkg1\sub_module1.py -&gt; build\lib\log_corp\sub_pkg1<br>running egg_info<br>writing src\log_corp1.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp1.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp1.egg-info\top_level.txt<br>reading manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp1.egg-info\SOURCES.txt&#39;<br>installing to build\bdist.win-amd64\wheel<br>running install<br>running install_lib<br>creating build\bdist.win-amd64\wheel<br>creating build\bdist.win-amd64\wheel\log_corp<br>copying build\lib\log_corp\module1.py -&gt; build\bdist.win-amd64\wheel\.\log_corp<br>creating build\bdist.win-amd64\wheel\log_corp\sub_pkg1<br>copying build\lib\log_corp\sub_pkg1\sub_module1.py -&gt; build\bdist.win-amd64\wheel\.\log_corp\sub_pkg1<br>running install_egg_info<br>Copying src\log_corp1.egg-info to build\bdist.win-amd64\wheel\.\log_corp1-1.0.1-py3.11.egg-info<br>running install_scripts<br>creating build\bdist.win-amd64\wheel\log_corp1-1.0.1.dist-info\WHEEL<br>creating &#39;C:\Users\L\Desktop\log_corp_comp1\dist\.tmp-ryh5ya6f\log_corp1-1.0.1-py3-none-any.whl&#39; and adding &#39;build\bdist.win-amd64\wheel&#39; to it<br>adding &#39;log_corp/module1.py&#39;<br>adding &#39;log_corp/sub_pkg1/sub_module1.py&#39;<br>adding &#39;log_corp1-1.0.1.dist-info/METADATA&#39;<br>adding &#39;log_corp1-1.0.1.dist-info/WHEEL&#39;<br>adding &#39;log_corp1-1.0.1.dist-info/top_level.txt&#39;<br>adding &#39;log_corp1-1.0.1.dist-info/RECORD&#39;<br>removing build\bdist.win-amd64\wheel<br><strong>Successfully built log_corp1-1.0.1.tar.gz </strong>and <strong>log_corp1-1.0.1-py3-none-any.whl</strong><br>PS C:\Users\L\Desktop\log_corp_comp1&gt;</pre><h4>Team 2(Repo 2)</h4><p>src layout</p><pre>LOG_CORP_COMP2/<br>├── src/<br>│   └── <strong>log_corp</strong>/<br>│       ├── sub_pkg2/<br>│       │   └── sub_module2.py<br>│       └── module2.py<br>├── pyproject.toml<br>└── README.md</pre><p><strong><em>module2.py</em></strong></p><pre>def func2():<br>    print(&#39;From log-corp module2&#39;)</pre><p><strong><em>sub_module2.py</em></strong></p><pre>def sub_func2():<br>    print(&#39;From log-corp submodule2&#39;)</pre><p><strong><em>pyproject.toml</em></strong></p><pre>[build-system]<br>requires = [&quot;setuptools&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;<br><br>[project]<br>name = &quot;log-corp2&quot;   # Different package name from the previous one<br>authors = [<br>    {name = &quot;Logesh&quot;, email = &quot;log@gmail.com&quot;},<br>]<br>description = &quot;My package description&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>license = {text = &quot;MIT License&quot;}<br>classifiers = [<br>    &quot;Programming Language :: Python :: 3&quot;,<br>]<br>version = &quot;1.0.2&quot;   # Different version </pre><h4>Built the package</h4><pre>PS E:\Documents\log_corp_comp2&gt; ls<br><br><br>    Directory: E:\Documents\log_corp_comp2<br><br><br>Mode                 LastWriteTime         Length Name<br>----                 -------------         ------ ----<br>d-----        12/28/2024  11:25 AM                src<br>-a----        12/28/2024  11:31 AM             34 README.md<br>-a----        12/28/2024  11:41 AM            387 pyproject.toml<br><br><br>PS E:\Documents\log_corp_comp2&gt; <strong>python -m build</strong><br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for sdist...<br>running egg_info<br>creating src\log_corp2.egg-info<br>writing src\log_corp2.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp2.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp2.egg-info\top_level.txt<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>reading manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>* Building sdist...<br>running sdist<br>running egg_info<br>writing src\log_corp2.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp2.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp2.egg-info\top_level.txt<br>reading manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>running check<br>creating log_corp2-1.0.2<br>creating log_corp2-1.0.2\src\log_corp<br>creating log_corp2-1.0.2\src\log_corp2.egg-info<br>creating log_corp2-1.0.2\src\log_corp\sub_pkg2<br>copying files to log_corp2-1.0.2...<br>copying README.md -&gt; log_corp2-1.0.2<br>copying pyproject.toml -&gt; log_corp2-1.0.2<br>copying src\log_corp\module2.py -&gt; log_corp2-1.0.2\src\log_corp<br>copying src\log_corp2.egg-info\PKG-INFO -&gt; log_corp2-1.0.2\src\log_corp2.egg-info<br>copying src\log_corp2.egg-info\SOURCES.txt -&gt; log_corp2-1.0.2\src\log_corp2.egg-info<br>copying src\log_corp2.egg-info\dependency_links.txt -&gt; log_corp2-1.0.2\src\log_corp2.egg-info<br>copying src\log_corp2.egg-info\top_level.txt -&gt; log_corp2-1.0.2\src\log_corp2.egg-info<br>copying src\log_corp\sub_pkg2\sub_module2.py -&gt; log_corp2-1.0.2\src\log_corp\sub_pkg2<br>Writing log_corp2-1.0.2\setup.cfg<br>Creating tar archive<br>removing &#39;log_corp2-1.0.2&#39; (and everything under it)<br>* Building wheel from sdist<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for wheel...<br>running egg_info<br>writing src\log_corp2.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp2.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp2.egg-info\top_level.txt<br>reading manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>* Building wheel...<br>running bdist_wheel<br>running build<br>running build_py<br>creating build\lib\log_corp<br>copying src\log_corp\module2.py -&gt; build\lib\log_corp<br>creating build\lib\log_corp\sub_pkg2<br>copying src\log_corp\sub_pkg2\sub_module2.py -&gt; build\lib\log_corp\sub_pkg2<br>running egg_info<br>writing src\log_corp2.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp2.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp2.egg-info\top_level.txt<br>reading manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>installing to build\bdist.win-amd64\wheel<br>running install<br>running install_lib<br>creating build\bdist.win-amd64\wheel<br>creating build\bdist.win-amd64\wheel\log_corp<br>copying build\lib\log_corp\module2.py -&gt; build\bdist.win-amd64\wheel\.\log_corp<br>creating build\bdist.win-amd64\wheel\log_corp\sub_pkg2<br>copying build\lib\log_corp\sub_pkg2\sub_module2.py -&gt; build\bdist.win-amd64\wheel\.\log_corp\sub_pkg2<br>running install_egg_info<br>Copying src\log_corp2.egg-info to build\bdist.win-amd64\wheel\.\log_corp2-1.0.2-py3.11.egg-info<br>running install_scripts<br>creating build\bdist.win-amd64\wheel\log_corp2-1.0.2.dist-info\WHEEL<br>creating &#39;E:\Documents\log_corp_comp2\dist\.tmp-bn0t41tx\log_corp2-1.0.2-py3-none-any.whl&#39; and adding &#39;build\bdist.win-amd64\wheel&#39; to it<br>adding &#39;log_corp/module2.py&#39;<br>adding &#39;log_corp/sub_pkg2/sub_module2.py&#39;<br>adding &#39;log_corp2-1.0.2.dist-info/METADATA&#39;<br>adding &#39;log_corp2-1.0.2.dist-info/WHEEL&#39;<br>adding &#39;log_corp2-1.0.2.dist-info/top_level.txt&#39;<br>adding &#39;log_corp2-1.0.2.dist-info/RECORD&#39;<br>removing build\bdist.win-amd64\wheel<br><strong>Successfully built log_corp2-1.0.2.tar.gz </strong>and <strong>log_corp2-1.0.2-py3-none-any.whl</strong><br>PS E:\Documents\log_corp_comp2&gt;</pre><h3>Using log_corp</h3><p>Creating virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsyDXcjf5Y-NhJFCIzKe-w.png" /></figure><h4>Installing one component of log-corp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_RzSwtfu5INyVFSlTKnfw.png" /></figure><h4>Installing another component of log-corp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ng0QMHPPRjSy-GmV9Bi8Ug.png" /></figure><p>So we have installed 2 different packages that share same namespace (main package). So, now these two packages <em>log_corp1 </em>and <em>log_corp2 </em>can be develop, distribute, install, upgrade, version independently. (Still sharing the same namespace, so called Namespace packages.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*gfRgO7WS8jPOn7lTSmfB-Q.png" /></figure><blockquote>Here the merging of the sources is automatically done during the installation and there is no conflicts during the merge. This is one of the major benefits of using Namespace packages.</blockquote><p>using the<strong><em> log-corp</em></strong> as a whole which is installed from different sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*dM8LM9YCM3TB8cLSs4iuJQ.png" /></figure><p>The one notable disadvantage is that <strong><em>import *</em></strong> to the <em>log_corp </em>won’t work as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HDYNIOsMbmF9bJT4Oi7uw.png" /></figure><p>Since there is no __init__.py file to initialize the package.</p><h3>Trying to achieve the same using the regular package</h3><p>Adding __init__.py for both the components and have some initialization in that file.</p><h4>Component 1</h4><pre>LOG_CORP_COMP1/<br>├── src/<br>│   └── <strong>log_corp</strong>/<br>│       ├── sub_pkg1/<br>│       │   ├── <strong>__init__</strong>.py<br>│       │   └── sub_module1.py<br>│       ├── <strong>__init__</strong>.py<br>│       └── module1.py<br>├── pyproject.toml<br>└── README.md</pre><p><strong><em>log_corp/__init__.py</em></strong></p><pre>from . import module1<br>from . import sub_pkg1</pre><p><strong><em>log_corp/sub_pkg1/__init__.py</em></strong></p><pre>from . import sub_module1</pre><p>Rest of the files has the same content.</p><h4>Component 2</h4><pre>LOG_CORP_COMP2/<br>├── src/<br>│   └── <strong>log_corp</strong>/<br>│       ├── sub_pkg2/<br>│       │   ├── <strong>__init__</strong>.py<br>│       │   └── sub_module2.py<br>│       ├── <strong>__init__</strong>.py<br>│       └── module2.py<br>├── pyproject.toml<br>└── README.md</pre><p><strong><em>log_corp/__init__.py</em></strong></p><pre>from . import module2<br>from . import sub_pkg2</pre><p><strong><em>log_corp/sub_pkg2/__init__.py</em></strong></p><pre>from . import sub_module2</pre><p>Rest of the files has the same content.</p><h4>Building both the packages</h4><h4>Component 1</h4><pre>PS C:\Users\L\Desktop\log_corp_comp1&gt; python -m build<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for sdist...<br>running egg_info<br>creating src\log_corp1.egg-info<br>&lt;...truncated output&gt;<br>removing build\bdist.win-amd64\wheel<br><strong>Successfully built log_corp1-1.0.1.tar.gz </strong>and <strong>log_corp1-1.0.1-py3-none-any.whl</strong><br>PS C:\Users\L\Desktop\log_corp_comp1&gt;<br>PS C:\Users\L\Desktop\log_corp_comp1&gt; ls<br><br><br>    Directory: C:\Users\L\Desktop\log_corp_comp1<br><br><br>Mode                 LastWriteTime         Length Name<br>----                 -------------         ------ ----<br>d-----        12/28/2024   1:31 PM                dist<br>d-----        12/28/2024   1:31 PM                src<br>-a----        12/28/2024  11:41 AM            387 pyproject.toml<br>-a----        12/28/2024  11:31 AM             34 README.md<br><br><br>PS C:\Users\L\Desktop\log_corp_comp1&gt;</pre><h4>Component 2</h4><pre>PS E:\Documents\log_corp_comp2&gt; python -m build<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for sdist...<br>running egg_info<br>creating src\log_corp2.egg-info<br>writing src\log_corp2.egg-info\PKG-INFO<br>writing dependency_links to src\log_corp2.egg-info\dependency_links.txt<br>writing top-level names to src\log_corp2.egg-info\top_level.txt<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>reading manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\log_corp2.egg-info\SOURCES.txt&#39;<br>* Building sdist...<br>running sdist<br>running egg_info<br>&lt;...truncated output&gt;<br>Writing log_corp2-1.0.2\setup.cfg<br>Creating tar archive<br>removing &#39;log_corp2-1.0.2&#39; (and everything under it)<br>* Building wheel from sdist<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for wheel...<br>running egg_info<br>&lt;...truncated output&gt;<br><strong>Successfully built log_corp2-1.0.2.tar.gz </strong>and <strong>log_corp2-1.0.2-py3-none-any.whl</strong><br>PS E:\Documents\log_corp_comp2&gt;</pre><h4>Usage</h4><p>Uninstalled the previoulsy installed packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taiX3jNr3_noR_zId0WU5g.png" /></figure><p>Installing package <strong><em>log_corp1</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1ZQefBfexDCDER6MTqt2g.png" /></figure><p>using it in a script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4-KaHj2ajT5Hddg-4_-yg.png" /><figcaption><strong><em>module1 </em></strong>and <strong>subpkg1 </strong>is accessible</figcaption></figure><p>Installing package <strong><em>log_corp2</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJ7dk2J6BCDR0dLbmpKfhg.png" /></figure><p>This installation acually overrides the <strong>log_corp/__init__.py</strong> file.</p><p>Now only the modules and subpackages from log_corp2 is available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Su16LVAdpPAoj6Elxi5EeQ.png" /></figure><p>But still we can access the packages/modules from the <strong><em>log_corp1 </em></strong>with the <strong>log_corp </strong>as the main package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9MkJgdXWgrce-PSWt7Taw.png" /></figure><p>The only thing to notice is that the <strong><em>log_corp/__init__.py </em></strong>is override by the <em>log_corp2</em>. So, if we have any critical initialization from <em>log_corp1 </em>will be affected which might lead to the package broken issue.</p><h3>Conclusion</h3><p>Namespace packages are a modern way to create flexible and extensible Python packages. They allow multiple parts of a package to reside in different directories or be distributed across multiple projects. This makes them ideal for large-scale projects, plugin systems, or situations where components are developed independently.</p><h4>Behavior with import *</h4><p>Namespace packages do not directly support wildcard imports (from package import *) because they lack an __init__.py file, where regular packages usually define the __all__ list to control what is imported.</p><h4>Pros of Namespace Packages</h4><ol><li><strong>Modularity</strong>: Different parts of the package can be split across multiple projects or directories.</li><li><strong>Scalability</strong>: Ideal for large systems with plugins or independently developed components.</li><li><strong>Ease of Maintenance</strong>: Enables updates to specific parts of a package without affecting the whole structure.</li><li><strong>No </strong><strong>__init__.py Requirement</strong>: Simplifies the creation of packages and avoids unnecessary boilerplate files.</li><li><strong>Improved Collaboration</strong>: Teams can work on different parts of the package in parallel, with each team owning its directory.</li></ol><h4>Cons of Namespace Packages</h4><ol><li><strong>No </strong><strong>__init__.py Features</strong>: Without an __init__.py file, you lose the ability to initialize the package, define default imports, or set up package-level logic.</li><li><strong>Complexity in Wildcard Imports</strong>: Does not support import *, leading to potential inconvenience in some use cases.</li><li><strong>Runtime Composition</strong>: Resolving the full package structure happens at runtime, which may cause subtle issues if directories are misconfigured.</li><li><strong>Debugging Challenges</strong>: With parts of the package spread across multiple locations, debugging and tracking down issues can be harder.</li></ol><p>Use namespace packages for distributed, modular systems or frameworks. For simpler projects or when compatibility with older Python versions is required, stick to regular packages.</p><p>Hope you have learned something new today!</p><p>Happie Learning!!</p><p>Cheers!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=985a8672e900" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/python-namespace-packages-985a8672e900">Python Namespace Packages</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Packaging — pyproject.toml]]></title>
            <link>https://towardsdev.com/python-packaging-pyproject-toml-50320189a06f?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/50320189a06f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyproject]]></category>
            <category><![CDATA[python-packaging]]></category>
            <category><![CDATA[setuptools]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 16:52:07 GMT</pubDate>
            <atom:updated>2024-12-31T12:35:57.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Packaging — pyproject.toml</h3><p>In this article, we are going to learn how to package our Python library/program for distribution(for others to use our package, like the ones we are installing and using via pip)</p><h3>Quick overview</h3><h4>Python modules</h4><p>A Python file, provided it only relies on the standard library, can be redistributed and reused. You will also need to ensure it’s written for the right version of Python, and only relies on the standard library.</p><p>This is great for sharing simple scripts and snippets between people who both have compatible Python versions (such as via email, StackOverflow, or GitHub gists).</p><h4>Python source distributions</h4><p>If your code consists of multiple Python files, it’s usually organized into a directory structure. Any directory containing Python files can comprise an <a href="https://packaging.python.org/en/latest/glossary/#term-Import-Package">Import Package</a>.</p><p>Because packages consist of multiple files, they are harder to distribute.</p><p>So long as your code contains nothing but pure Python code, and you know your deployment environment supports your version of Python, then you can use Python’s native packaging tools to create a <em>source</em> <a href="https://packaging.python.org/en/latest/glossary/#term-Distribution-Package">Distribution Package</a>, or <em>sdist</em> for short.</p><p>Python’s <em>sdists</em> are compressed archives (.tar.gz files) containing one or more packages or modules</p><h4>Python binary distributions</h4><p>So much of Python’s practical power comes from its ability to integrate with the software ecosystem, in particular libraries written in C, C++, Fortran, Rust, and other languages.</p><p>Not all developers have the right tools or experiences to build these components written in these compiled languages, so Python created the <a href="https://packaging.python.org/en/latest/glossary/#term-Wheel">Wheel</a>, a package format designed to ship libraries with compiled artifacts. In fact, Python’s package installer, pip, always prefers wheels because installation is always faster, so even pure-Python packages work better with wheels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*1fCndBxiZvoB080FDyntFA.png" /><figcaption><a href="https://packaging.python.org/en/latest/overview/">src</a></figcaption></figure><h3>pyproject.toml</h3><p>We are going to use <strong>pyproject.toml </strong>file for building and distributing our Python packages.</p><blockquote>Note: We can also use setup.py, setup.cfg to achieve the same.</blockquote><p>The pyproject.toml file is a configuration file for Python projects. The file is written in the <strong>TOML</strong> (Tom’s Obvious, Minimal Language) format, which is designed to be simple and human-readable.</p><h4>Key Sections in pyproject.toml</h4><ul><li>[build-system]: Specifies the build backend and dependencies required for building the project.</li><li>[project]: (PEP 621) Metadata about the project, such as name, version, authors, and dependencies.</li><li>[tool.&lt;tool_name&gt;]: Configuration for various tools like pytest, black, etc.</li></ul><p><strong>Build Tools</strong></p><ul><li>setuptools: Traditional Python build tool.</li><li>poetry: Modern dependency management and packaging.</li><li>flit: Lightweight tool for publishing Python packages.</li></ul><h4>Sample project</h4><p>Lets create our Python project which we are going to distribute.</p><p>Before creating our Project we have to decide the project structure(layout).</p><p>There are two types of layouts:</p><ol><li><strong>src layout</strong> — The project should contain a src directory under the project root and all modules and packages meant for distribution are placed inside this directory</li></ol><pre>project_root_directory<br>├── pyproject.toml  # AND/OR setup.cfg, setup.py<br>├── ...<br>└── src/<br>    └── mypkg/<br>        ├── __init__.py<br>        ├── ...<br>        ├── module.py<br>        ├── subpkg1/<br>        │   ├── __init__.py<br>        │   ├── ...<br>        │   └── module1.py<br>        └── subpkg2/<br>            ├── __init__.py<br>            ├── ...<br>            └── module2.py</pre><p>This layout is very handy when you wish to use automatic discovery, since you don’t have to worry about other Python files or folders in your project root being distributed by mistake.</p><p>2. <strong>flat layout</strong> — The package folder(s) are placed directly under the project root <em>(also known as “adhoc”)</em></p><pre>project_root_directory<br>├── pyproject.toml  # AND/OR setup.cfg, setup.py<br>├── ...<br>└── mypkg/<br>    ├── __init__.py<br>    ├── ...<br>    ├── module.py<br>    ├── subpkg1/<br>    │   ├── __init__.py<br>    │   ├── ...<br>    │   └── module1.py<br>    └── subpkg2/<br>        ├── __init__.py<br>        ├── ...<br>        └── module2.py</pre><p>Reference: <a href="https://setuptools.pypa.io/en/stable/userguide/package_discovery.html">https://setuptools.pypa.io/en/stable/userguide/package_discovery.html</a></p><p>Lets choose<strong> src layout.</strong></p><pre>SUPERPROJECT/<br>├── src/<br>│   └── super_package/<br>│       ├── __init__.py<br>│       └── super_module.py<br>├── pyproject.toml<br>└── README.md</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*gobl5vwr1y0SwDNgRCsIUA.png" /><figcaption>super_module.py content</figcaption></figure><p>Lets write our pyproject.toml file</p><h4>build-system</h4><ul><li>requires: Specifies dependencies needed for the build process.</li><li>build-backend: Specifies the tool/module that handles building the project.</li></ul><pre>[build-system]<br>requires = [&quot;setuptools&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;</pre><h4>project</h4><pre>[project]<br>name = &quot;super-pkg&quot;   # as it would appear on PyPI<br>authors = [<br>    {name = &quot;Logesh&quot;, email = &quot;log@gmail.com&quot;},<br>]<br>description = &quot;My package description&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>license = {text = &quot;MIT License&quot;}<br>classifiers = [<br>    &quot;Programming Language :: Python :: 3&quot;,<br>]<br>dependencies = [<br>    &quot;requests&quot;,<br>]<br>version = &quot;1.0.1&quot;</pre><p>For more options check <a href="https://packaging.python.org/en/latest/guides/writing-pyproject-toml/">here</a> and <a href="https://setuptools.pypa.io/en/stable/userguide/pyproject_config.html">here</a></p><h4>tool</h4><p>For the src layout we majorly don’t need the tool section. Since all our packages meant for distribution were placed unser src dir. So the automatic discovery can find the available packages from the src dir.</p><p>If we chose the flat-layout then tool section might be helpful in providing the info about the packages path(where to find), what are all the packages been included/ excluded.</p><pre>[tool.setuptools.packages.find]<br>where = [&quot;src&quot;]  # list of folders that contain the packages ([&quot;.&quot;] by default)<br>include = [&quot;my_package*&quot;]  # package names should match these glob patterns ([&quot;*&quot;] by default)<br>exclude = [&quot;my_package.tests*&quot;]  # exclude packages matching these glob patterns (empty by default)<br>namespaces = false  # to disable scanning PEP 420 namespaces (true by default)</pre><h4>our pyproject.toml file</h4><pre>[build-system]<br>requires = [&quot;setuptools&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;<br><br>[project]<br>name = &quot;super-pkg&quot;<br>authors = [<br>    {name = &quot;Logesh&quot;, email = &quot;log@gmail.com&quot;},<br>]<br>description = &quot;My package description&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>license = {text = &quot;MIT License&quot;}<br>classifiers = [<br>    &quot;Programming Language :: Python :: 3&quot;,<br>]<br>dependencies = [<br>    &quot;requests&quot;,<br>]<br>version = &quot;1.0.1&quot;</pre><h4>Build our package</h4><p>To build our Python package we can use <strong>setup.py</strong> or <strong>build </strong>module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0boQkyYCnKzHbFFKjf7dUw.png" /><figcaption><a href="https://packaging.python.org/en/latest/guides/modernize-setup-py-project/"><strong>src</strong></a></figcaption></figure><p>To use <strong>build </strong>module, we have install that using</p><pre>pip install build</pre><p>Once we have our build module we can build our package by running the build command in our project root dir.</p><pre>python -m build</pre><p>Command execution output</p><pre>PS C:\Users\L\Desktop\SuperProject&gt; ls<br><br><br>    Directory: C:\Users\L\Desktop\SuperProject<br><br><br>Mode                 LastWriteTime         Length Name<br>----                 -------------         ------ ----<br>d-----        12/27/2024   9:12 PM                src<br>-a----        12/27/2024   9:19 PM            436 pyproject.toml<br>-a----        12/27/2024   9:22 PM             31 README.md<br><br><br>PS C:\Users\L\Desktop\SuperProject&gt; python -m build<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for sdist...<br>running egg_info<br>creating src\super_pkg.egg-info<br>writing src\super_pkg.egg-info\PKG-INFO<br>writing dependency_links to src\super_pkg.egg-info\dependency_links.txt<br>writing requirements to src\super_pkg.egg-info\requires.txt<br>writing top-level names to src\super_pkg.egg-info\top_level.txt<br>writing manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>reading manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>* Building sdist...<br>running sdist<br>running egg_info<br>writing src\super_pkg.egg-info\PKG-INFO<br>writing dependency_links to src\super_pkg.egg-info\dependency_links.txt<br>writing requirements to src\super_pkg.egg-info\requires.txt<br>writing top-level names to src\super_pkg.egg-info\top_level.txt<br>reading manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>running check<br>creating super_pkg-1.0.1<br>creating super_pkg-1.0.1\src\super_package<br>creating super_pkg-1.0.1\src\super_pkg.egg-info<br>copying files to super_pkg-1.0.1...<br>copying README.md -&gt; super_pkg-1.0.1<br>copying pyproject.toml -&gt; super_pkg-1.0.1<br>copying src\super_package\__init__.py -&gt; super_pkg-1.0.1\src\super_package<br>copying src\super_package\super_module.py -&gt; super_pkg-1.0.1\src\super_package<br>copying src\super_pkg.egg-info\PKG-INFO -&gt; super_pkg-1.0.1\src\super_pkg.egg-info<br>copying src\super_pkg.egg-info\SOURCES.txt -&gt; super_pkg-1.0.1\src\super_pkg.egg-info<br>copying src\super_pkg.egg-info\dependency_links.txt -&gt; super_pkg-1.0.1\src\super_pkg.egg-info<br>copying src\super_pkg.egg-info\requires.txt -&gt; super_pkg-1.0.1\src\super_pkg.egg-info<br>copying src\super_pkg.egg-info\top_level.txt -&gt; super_pkg-1.0.1\src\super_pkg.egg-info<br>copying src\super_pkg.egg-info\SOURCES.txt -&gt; super_pkg-1.0.1\src\super_pkg.egg-info<br>Writing super_pkg-1.0.1\setup.cfg<br>Creating tar archive<br>removing &#39;super_pkg-1.0.1&#39; (and everything under it)<br>* Building wheel from sdist<br>* Creating isolated environment: venv+pip...<br>* Installing packages in isolated environment:<br>  - setuptools<br>* Getting build dependencies for wheel...<br>running egg_info<br>writing src\super_pkg.egg-info\PKG-INFO<br>writing dependency_links to src\super_pkg.egg-info\dependency_links.txt<br>writing requirements to src\super_pkg.egg-info\requires.txt<br>writing top-level names to src\super_pkg.egg-info\top_level.txt<br>reading manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>* Building wheel...<br>running bdist_wheel<br>running build<br>running build_py<br>creating build\lib\super_package<br>copying src\super_package\super_module.py -&gt; build\lib\super_package<br>copying src\super_package\__init__.py -&gt; build\lib\super_package<br>running egg_info<br>writing src\super_pkg.egg-info\PKG-INFO<br>writing dependency_links to src\super_pkg.egg-info\dependency_links.txt<br>writing requirements to src\super_pkg.egg-info\requires.txt<br>writing top-level names to src\super_pkg.egg-info\top_level.txt<br>reading manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>writing manifest file &#39;src\super_pkg.egg-info\SOURCES.txt&#39;<br>installing to build\bdist.win-amd64\wheel<br>running install<br>running install_lib<br>creating build\bdist.win-amd64\wheel<br>creating build\bdist.win-amd64\wheel\super_package<br>copying build\lib\super_package\super_module.py -&gt; build\bdist.win-amd64\wheel\.\super_package<br>copying build\lib\super_package\__init__.py -&gt; build\bdist.win-amd64\wheel\.\super_package<br>running install_egg_info<br>Copying src\super_pkg.egg-info to build\bdist.win-amd64\wheel\.\super_pkg-1.0.1-py3.11.egg-info<br>running install_scripts<br>creating build\bdist.win-amd64\wheel\super_pkg-1.0.1.dist-info\WHEEL<br>creating &#39;C:\Users\L\Desktop\SuperProject\dist\.tmp-m6_z1ckk\super_pkg-1.0.1-py3-none-any.whl&#39; and adding &#39;build\bdist.win-amd64\wheel&#39; to it<br>adding &#39;super_package/__init__.py&#39;<br>adding &#39;super_package/super_module.py&#39;<br>adding &#39;super_pkg-1.0.1.dist-info/METADATA&#39;<br>adding &#39;super_pkg-1.0.1.dist-info/WHEEL&#39;<br>adding &#39;super_pkg-1.0.1.dist-info/top_level.txt&#39;<br>adding &#39;super_pkg-1.0.1.dist-info/RECORD&#39;<br>removing build\bdist.win-amd64\wheel<br>Successfully built super_pkg-1.0.1.tar.gz and super_pkg-1.0.1-py3-none-any.whl<br>PS C:\Users\L\Desktop\SuperProject&gt;<br>PS C:\Users\L\Desktop\SuperProject&gt;<br>PS C:\Users\L\Desktop\SuperProject&gt; ls<br><br><br>    Directory: C:\Users\L\Desktop\SuperProject<br><br><br>Mode                 LastWriteTime         Length Name<br>----                 -------------         ------ ----<br>d-----        12/27/2024   9:36 PM                dist<br>d-----        12/27/2024   9:35 PM                src<br>-a----        12/27/2024   9:19 PM            436 pyproject.toml<br>-a----        12/27/2024   9:22 PM             31 README.md<br><br><br>PS C:\Users\L\Desktop\SuperProject&gt;</pre><p><strong>dist </strong>dir is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*S-WgVEzKKX4pi8PcD5Vymg.png" /><figcaption>after building the package</figcaption></figure><p>Now, we can locally install this package using <strong>whl</strong> file or <strong>tar.gz</strong> file</p><p>Lets create one test script in that we can install and use this package.</p><p>Creating virtual env</p><pre>python -m venv venv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYuCfF9FzLh5KGDVxp6e7Q.png" /><figcaption>create and activate venv</figcaption></figure><p>Now we can install our package using the whl file</p><pre>pip install &lt;path-to-whl-file-or-tar.gz-file&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HABJt6RaWEvEFgpU9wBKXA.png" /><figcaption>our super_package is installed.</figcaption></figure><p>Using our package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcKb8PUt6tfJm-DDyTK6Ag.png" /></figure><p>So far we have learned how to build and install our package locally using pyproject.toml</p><p>To upload the package to PyPi please refer,</p><ul><li><a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives">https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives</a></li></ul><p>For extensions</p><ul><li><a href="https://setuptools.pypa.io/en/stable/userguide/ext_modules.html">https://setuptools.pypa.io/en/stable/userguide/ext_modules.html</a></li></ul><p>Hope you learned something new today!</p><p>Happie learning</p><p>Cheers!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50320189a06f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/python-packaging-pyproject-toml-50320189a06f">Python Packaging — pyproject.toml</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cooperative multitasking — Asyncio]]></title>
            <link>https://towardsdev.com/cooperative-multitasking-asyncio-e142bd6b044a?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/e142bd6b044a</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[multitasking]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 19:44:00 GMT</pubDate>
            <atom:updated>2024-11-25T16:40:11.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cooperative multitasking — Asyncio</h3><p>In my <a href="https://towardsdev.com/python-asyncio-5505827fb840">previous article</a> we learned about the Python Asyncio basics.</p><p>In this one, will look into the working of Cooperative multitasking with an example.</p><p><strong>Cooperative multitasking</strong>, also known as <strong>non-preemptive multitasking</strong>, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, in order to run multiple applications concurrently, <strong>processes voluntarily yield control periodically or when idle or logically blocked</strong>. This type of multitasking is called <em>cooperative</em> because all programs must cooperate for the scheduling scheme to work. — <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking#:~:text=Cooperative%20multitasking%2C%20also%20known%20as,running%20process%20to%20another%20process.">Src</a></p><blockquote><strong>processes voluntarily yield control periodically or when idle or logically blocked to achieve concurrency</strong></blockquote><p>Lets understand this with the below example.</p><pre><br>import asyncio<br><br>async def big_task():<br>    for i in range(10 ** 10):<br>        print(i, end=&quot; &quot;)<br><br>async def sleep_task():<br>    await asyncio.sleep(1)<br><br><br>async def main():<br>    task = asyncio.create_task(big_task())<br>    st = asyncio.create_task(sleep_task())<br>    await st<br>    task.cancel()<br>    print(&quot;Task cancelled&quot;)<br>    await task<br><br>asyncio.run(main())</pre><p>In the above example, we have a <strong>big_task </strong>which does some biggggg work(assume). I have created a aysncio task for that and created another task which sleeps for 1 sec and then I try to cancel the big_task and print “Task cancelled” and then awaited for the cancelled task(which will throw an error, since await is used on the cancelled task).</p><p>But when I execute the script, some unexpected thing happen….</p><p>The script continues to execute till the end. The big_task is not cancelled after 1 sec.</p><p>Lets change a code little bit.</p><pre>import asyncio<br><br>async def big_task():<br>    for i in range(10 ** 10):<br>        print(i, end=&quot; &quot;)<br>        if i == 10_000:<br>            await asyncio.sleep(1.1)<br><br>async def sleep_task():<br>    await asyncio.sleep(1)<br><br><br>async def main():<br>    task = asyncio.create_task(big_task())<br>    st = asyncio.create_task(sleep_task())<br>    await st<br>    task.cancel()<br>    print(&quot;Task cancelled&quot;)<br>    await task<br><br>asyncio.run(main())</pre><p>here in the <strong>big_task </strong>function i have added a asyncio sleep for <strong>1.1 sec</strong> when<strong><em> i</em></strong> equals 10,000. This actually blocks the big_task for 1.1 sec, so the <em>big_task</em> <strong>yield control to</strong> <em>sleep_task, </em>and the sleep_task sleeps for 1 sec and then cancelled the big_task in that 0.1 sec. Now, our code works the way we expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-uiviT_M3uBKB46tVs-6g.png" /><figcaption>output</figcaption></figure><p>If the <em>big_task </em><strong>doesn’t have enough blockage</strong> for the <em>sleep_task </em>to complete and cancel the big_task, it will be the same scenario as the first one.</p><p>I mean, if the sleep in big_task is less then or equal to 1 then the script will run <em>big_task </em>completely. Becoz, the sleep_task will not get a chance to complete and then the cancel to execute.</p><p>Now that we understand the <strong>Cooperative multitasking</strong>. Which clearly says that asyncio is not Parallelism but it is Concurrent.</p><p>Happie Learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e142bd6b044a" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/cooperative-multitasking-asyncio-e142bd6b044a">Cooperative multitasking — Asyncio</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Asyncio]]></title>
            <link>https://towardsdev.com/python-asyncio-5505827fb840?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/5505827fb840</guid>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 06:09:52 GMT</pubDate>
            <atom:updated>2024-11-18T18:31:57.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*_qfOKUow37i0GiJOT1MX0Q.png" /></figure><h3>asyncio — Asynchronous I/O</h3><p><strong>asyncio </strong>is the Python package which is used to achieve Asynchronous programming model.</p><p>In an asynchronous programming model, when one task gets executed, you could switch to a different task without waiting for the previous to get completed.</p><blockquote>async IO is a single-threaded, single-process design: it uses <strong>cooperative multitasking</strong></blockquote><p><strong>Cooperative multitasking</strong>, also known as <strong>non-preemptive multitasking</strong>, is a style of <a href="https://en.wikipedia.org/wiki/Computer_multitasking">computer multitasking</a> in which the <a href="https://en.wikipedia.org/wiki/Operating_system">operating system</a> never initiates a <a href="https://en.wikipedia.org/wiki/Context_switch">context switch</a> from a running <a href="https://en.wikipedia.org/wiki/Process_(computing)">process</a> to another process. Instead, in order to run multiple applications concurrently, <strong>processes voluntarily </strong><a href="https://en.wikipedia.org/wiki/Yield_(multithreading)"><strong>yield control</strong></a><strong> periodically or when idle or logically </strong><a href="https://en.wikipedia.org/wiki/Blocking_(computing)"><strong>blocked</strong></a>. This type of multitasking is called <em>cooperative</em> because all programs must cooperate for the scheduling scheme to work. — <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking#:~:text=Cooperative%20multitasking%2C%20also%20known%20as,running%20process%20to%20another%20process.">Src</a></p><p>asyncio enables to handle multiple tasks efficiently, particularly I/O-bound and network-bound operations, without using traditional multithreading or multiprocessing.</p><blockquote>Asynchronous example</blockquote><blockquote>Imagine you were given to make a sandwich and wash your clothes in a washing machine. You could put your clothes in the washing machine and without waiting for it to be done, you could go and make the sandwich. Here you performed these<strong> two tasks asynchronously</strong>.</blockquote><h3>Then what is Synchronous?</h3><p>In a synchronous programming model, tasks are executed one after another. Each task waits for any previous task to complete and then gets executed.</p><h3>What about <strong>Parallelism, </strong>Concurrency, <strong>Threading?</strong></h3><h4>Parallelism</h4><p>Performing multiple operations at the same time.</p><ul><li>Parallelism is achieved by <strong>multi-processing</strong>, by spreading tasks over a computer’s central processing units (CPUs, or cores). Multiprocessing is well-suited for CPU-bound tasks</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUxSbB8mfsnFNexn_y1prw.png" /></figure><h4><strong>Concurrency</strong></h4><p>Performing multiple tasks or operations at the same time but not necessarily run simultaneously (in parallel) but instead progress by interleaving execution steps, often sharing resources like a CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kONFrUpxtOiWHCpgKnR3Sw.png" /></figure><p><strong>Threading</strong> is a concurrent execution model whereby multiple <a href="https://en.wikipedia.org/wiki/Thread_(computing)">threads</a> take turns executing tasks. One process can contain multiple threads</p><p>So, multi-threading has multiple threads doing separate task simultaneously but not at the same time. Since its using the same memory and cpu. Well suited for I/O bounded tasks.</p><h3>Asyncio</h3><p>async IO gives a feeling of concurrency despite using a single thread in a single process. To reiterate, async IO is a style of concurrent programming, but it is not parallelism. It’s more closely aligned with threading than with multiprocessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*aLOMDWx8VOs8G9beRXTc3Q.png" /><figcaption><a href="https://realpython.com/async-io-python">https://realpython.com/async-io-python</a></figcaption></figure><h3>Key Features of asyncio</h3><p><strong>1. Concurrency without Threads or Processes</strong>:</p><ul><li>Uses a single-threaded event loop to schedule and manage tasks.</li><li>Tasks do not block the event loop when waiting for I/O, allowing other tasks to execute.</li></ul><p><strong>2. Coroutines and </strong><strong>await Syntax</strong>:</p><ul><li>Coroutines are special functions that can pause and resume execution.</li><li>The await keyword is used to call asynchronous operations, pausing the coroutine until the operation is complete.</li></ul><p><strong>3. Efficient for I/O-bound Tasks</strong>:</p><ul><li>Ideal for programs involving file reading, database queries, HTTP requests, or other I/O-intensive operations.</li></ul><p><strong>4. High-level APIs</strong>:</p><ul><li>Task management with asyncio.create_task(), asyncio.gather(), etc.</li><li>Timeout handling with asyncio.timeout() and asyncio.wait_for().</li></ul><h4>What is Coroutine?</h4><blockquote><strong>Coroutines</strong> are <a href="https://en.wikipedia.org/wiki/Computer_program">computer program</a> components that allow execution to be suspended and resumed, generalizing <a href="https://en.wikipedia.org/wiki/Subroutine">subroutines</a> for <a href="https://en.wikipedia.org/wiki/Non-preemptive_multitasking">cooperative multitasking</a>. Coroutines are well-suited for implementing familiar program components such as <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking">cooperative tasks</a>, <a href="https://en.wikipedia.org/wiki/Exception_handling">exceptions</a>, <a href="https://en.wikipedia.org/wiki/Event_loop">event loops</a>, <a href="https://en.wikipedia.org/wiki/Iterator">iterators</a>, <a href="https://en.wikipedia.org/wiki/Lazy_evaluation">infinite lists</a> and <a href="https://en.wikipedia.org/wiki/Pipeline_(software)">pipes</a>.</blockquote><blockquote>They have been described as “functions whose execution you can pause” — <a href="https://en.wikipedia.org/wiki/Coroutine">src</a></blockquote><p>A coroutine is a special type of function defined with async def. It represents an asynchronous operation that can pause (await) and resume.</p><pre>from datetime import datetime<br>import time<br>import asyncio<br><br>async def say(msg, *, delay): # coroutine<br>    print(f&quot;Started {datetime.now():%H:%M:%S}&quot;)<br>    await asyncio.sleep(delay=delay)<br>    print(msg)<br>    print(f&quot;Ended {datetime.now():%H:%M:%S}&quot;)<br>    return f&#39;Returned - {msg}&#39;<br><br>start = time.perf_counter()<br>r1 = asyncio.run(say(&#39;Logesh&#39;, delay=2)) # Run the coroutine and returns result<br>print(r1)<br>r2 = asyncio.run(say(&#39;Sakthivel&#39;, delay=4))<br>print(r2)<br>end = time.perf_counter()<br>print(f&#39;Total execution time: {end-start}s&#39;)<br><br># Output:<br># Started 09:28:22<br># Logesh<br># Ended 09:28:24<br># Returned - Logesh<br># Started 09:28:24<br># Sakthivel<br># Ended 09:28:28<br># Returned - Sakthivel<br># Total execution time: 6.018443500000103s</pre><p>Here, in the above example we have used the simple asyncio coroutine.</p><p>But there is no use. Since it take 6 secs to execute which is like of synchronous model. await is the blocking code.</p><p>To make it asynchronous we should Schedule tasks concurrently.</p><h4>Run many awaitables as group</h4><p>The execution of multiple coroutines, scheduling them to run when they are ready and handling I/O operations efficiently can be done usingasyncio.gather() which takes multiple coroutines.</p><pre>from datetime import datetime<br>import time<br>import asyncio<br><br>async def say(msg, *, delay): # coroutine<br>    print(f&quot;Started {datetime.now():%H:%M:%S}&quot;)<br>    await asyncio.sleep(delay=delay)<br>    print(msg)<br>    print(f&quot;Ended {datetime.now():%H:%M:%S}&quot;)<br>    return f&#39;Returned - {msg}&#39;<br><br>async def gather():<br>    # Schedule tasks concurrently. Event loop<br>    gather_list = asyncio.gather(<br>        say(&#39;gather lol&#39;, delay=2),<br>        say(&#39;gather lol2&#39;, delay=4),<br>    )<br>    out_list = await gather_list<br>    print(gather_list) # object<br>    print(out_list) # results<br><br>start = time.perf_counter()<br>asyncio.run(gather())<br>end = time.perf_counter()<br>print(f&#39;Total execution time: {end-start}s&#39;)<br><br># output<br># Started 09:47:55<br># Started 09:47:55<br># gather lol<br># Ended 09:47:57<br># gather lol2<br># Ended 09:47:59<br># &lt;_GatheringFuture finished result=[&#39;Returned - gather lol&#39;, &#39;Returned - gather lol2&#39;]&gt;<br># [&#39;Returned - gather lol&#39;, &#39;Returned - gather lol2&#39;]<br># Total execution time: 4.008762699999352s</pre><p>Here is the true asynchronous. Execution time is almost 4secs.</p><h4>Task</h4><p>A Task is a wrapper around a coroutine, allowing it to run concurrently with other tasks. Created using asyncio.create_task()</p><pre>from datetime import datetime<br>import time<br>import asyncio<br><br>async def say(msg, *, delay): # coroutine<br>    print(f&quot;Started {datetime.now():%H:%M:%S}&quot;)<br>    await asyncio.sleep(delay=delay)<br>    print(msg)<br>    print(f&quot;Ended {datetime.now():%H:%M:%S}&quot;)<br>    return f&#39;Returned - {msg}&#39;<br><br>async def simple_task():<br>    task1 = asyncio.create_task(say(&#39;Task1 lol&#39;,delay=4))<br>    task2 = asyncio.create_task(say(&#39;Task2 lol&#39;,delay=2))<br>    r1 = await task1 # blocking code<br>    print(r1)<br>    r2 = await task2<br>    print(r2)<br><br>start = time.perf_counter()<br>asyncio.run(simple_task())<br>end = time.perf_counter()<br>print(f&#39;Total execution time: {end-start}s&#39;)<br><br># Output<br># Started 09:52:36<br># Started 09:52:36<br># Task2 lol<br># Ended 09:52:38<br># Task1 lol<br># Ended 09:52:40<br># Returned - Task1 lol<br># Returned - Task2 lol<br># Total execution time: 4.006176800000503s</pre><p>Here we have created a concurrent task. Task1 has 4 sec delay, Task2 has 2 sec delay. Task1 started and then Task2 is started.</p><p>However Task2 finished its execution first.</p><pre>task1 = asyncio.create_task(say(&#39;Task1 lol&#39;,delay=4))<br>task2 = asyncio.create_task(say(&#39;Task2 lol&#39;,delay=2))<br>r1 = await task1 # blocking code<br>print(r1)<br>r2 = await task2 # blocking code<br>print(r2)</pre><p><em>This piece of code has lot to understand.</em></p><p><strong>Task1 </strong>is started, then <strong>Task2</strong>. In line no. 3 we are waiting for the <em>task1 </em>to complete and return the result and then only it will execute next line. Meanwhile <em>task2 </em>is being executed while waiting for <em>task1 </em>but the return value of <em>task2 </em>is not fetched since <em>task1 </em>needs to give control (completes its execution). Once <em>task1 </em>is comepleted and returns the value, we then get the return value from the <em>task2 </em>which is completed before <em>task1</em>.</p><h4>Synchronization Primitives</h4><p>asyncio provides tools for synchronization, such as locks, semaphores, and queues, to manage shared resources among coroutines.</p><pre>from datetime import datetime<br>import time<br>import asyncio<br><br>lock = asyncio.Lock()<br><br>async def say(msg, *, delay):<br>    # lock the resource. only one coroutine can access this block at a given time<br>    async with lock:<br>        print(f&quot;Started {datetime.now():%H:%M:%S}&quot;)<br>        await asyncio.sleep(delay=delay)<br>        print(msg)<br>        print(f&quot;Ended {datetime.now():%H:%M:%S}&quot;)<br>        return f&#39;Returned - {msg}&#39;<br><br>async def simple_task():<br>    task1 = asyncio.create_task(say(&#39;Task1 lol&#39;,delay=4))<br>    task2 = asyncio.create_task(say(&#39;Task2 lol&#39;,delay=2))<br>    r1 = await task1<br>    print(r1)<br>    r2 = await task2<br>    print(r2)<br><br>start = time.perf_counter()<br>asyncio.run(simple_task())<br>end = time.perf_counter()<br>print(f&#39;Total execution time: {end-start}s&#39;)<br><br># Output<br># Started 10:06:21<br># Task1 lol<br># Ended 10:06:25<br># Started 10:06:25<br># Returned - Task1 lol<br># Task2 lol<br># Ended 10:06:27<br># Returned - Task2 lol<br># Total execution time: 6.015326099999584s</pre><p>It is executed as Synchronous model. Since locking is used, only one corountine can execute that particular block at a given time.</p><h4>Cancel task</h4><p>Once the task is scheduled, we can cancel that task.</p><pre>from datetime import datetime<br>import asyncio<br><br>async def say(msg, *, delay):<br>    print(f&quot;Started {datetime.now():%H:%M:%S}&quot;)<br>    await asyncio.sleep(delay=delay)<br>    print(msg)<br>    print(f&quot;Ended {datetime.now():%H:%M:%S}&quot;)<br>    return f&#39;Returned - {msg}&#39;<br><br>async def task():<br>    task1 = asyncio.create_task(say(&#39;lol&#39;,delay=5))<br>    await asyncio.sleep(2)<br>    task1.cancel(&#39;Took too long...&#39;) # cancel the task with message<br>    try:<br>        print(&#39;Waiting for the task after cancel&#39;)<br>        await task1<br>    except asyncio.CancelledError as ce:<br>        print(&#39;Exception occured&#39;)<br>        print(ce)<br>    print(f&#39;{task1.cancelled()=}&#39;) # we can also check whether the task is cancelled<br><br>asyncio.run(task())<br><br># Output<br># Started 11:09:24<br># Waiting for the task after cancel<br># Exception occured<br># Took too long...<br># task1.cancelled()=True</pre><h4>Adding callback</h4><p>We could also add the callback function to the task. Once the task is done, the callback function is called with the task as its argument.</p><pre>from datetime import datetime<br>import asyncio<br><br><br>async def say(msg, *, delay):<br>    print(f&quot;Started {datetime.now():%H:%M:%S}&quot;)<br>    await asyncio.sleep(delay=delay)<br>    print(msg)<br>    print(f&quot;Ended {datetime.now():%H:%M:%S}&quot;)<br>    return f&#39;Returned - {msg}&#39;<br><br>async def task():<br>    taskset = set() # set to track the number of tasks<br>    task1 = asyncio.create_task(say(&#39;lol&#39;,delay=5))<br>    task2 = asyncio.create_task(say(&#39;lol2&#39;,delay=10))<br>    taskset.add(task1)<br>    taskset.add(task2)<br>    print(f&#39;Number of tasks: {len(taskset)}&#39;)<br>    task1.add_done_callback(taskset.discard) # once the task is done the callback function is called.<br>    task2.add_done_callback(taskset.discard)<br>    await task1<br>    print(f&#39;Number of pending tasks: {len(taskset)}&#39;)<br>    print(f&#39;{task1.done()=}&#39;)<br>    await task2<br>    print(f&#39;Number of pending tasks: {len(taskset)}&#39;)<br>    print(f&#39;{task2.done()=}&#39;)<br><br>asyncio.run(task())<br><br># Output<br># Number of tasks: 2<br># Started 11:15:37<br># Started 11:15:37<br># lol<br># Ended 11:15:42<br># Number of pending tasks: 1<br># task1.done()=True<br># lol2<br># Ended 11:15:47<br># Number of pending tasks: 0<br># task2.done()=True</pre><p>A callable function that accepts a single argument — the Future or Task object itself. If the callback function returns a value, it is ignored. The return value is not stored or passed back into the Future or Task.</p><h4>Timeout handling</h4><p>asyncio.wait_for()takes task and timeout in seconds (float) as the arguments. It will wait for the given time(seconds), if the task is not done it will raise Timeout error.</p><pre>async def task():<br>    task1 = asyncio.create_task(say(&#39;lol&#39;,delay=5))<br>    try:<br>        result = await asyncio.wait_for(task1, 2) <br>        # this will raise the timeout error since we haven&#39;t provided enough time to complete the task<br>    except asyncio.TimeoutError as te:<br>        print(&#39;Timeout error occurs&#39;)<br><br>asyncio.run(task())<br># output<br># Started 11:22:59<br># Timeout error occurs</pre><h3>Wrapping up</h3><p>asyncio is a powerful tool for handling asynchronous programming in Python. It is best suited for tasks that involve high I/O or concurrency needs</p><p>Hope you learned something new.</p><p>Happie Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5505827fb840" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/python-asyncio-5505827fb840">Python Asyncio</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[General Boot process — explained]]></title>
            <link>https://medium.com/@LogeshSakthivel/general-boot-process-explained-b77a61dccc49?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/b77a61dccc49</guid>
            <category><![CDATA[boots]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[booting]]></category>
            <category><![CDATA[booting-sequence]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 16:12:10 GMT</pubDate>
            <atom:updated>2024-04-19T16:19:54.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>General Boot process — explained</h3><p>In this post, I hope to discuss the general booting model procedure, which took me longer to comprehend after researching several websites and getting at least the essential details so you won’t have to go through it.</p><p>Note: The process explained here is the old school method using BIOS. And there is no strict standards that enforces all the devices to boot in the sameway. It differs with the implementation, technologies, the hardware architecture, etc..,</p><h3>Tech Terms</h3><h4>Booting</h4><p>Booting refers to the process by which a computer initializes its hardware components and loads the operating system into its main memory, making the system ready for operations. It’s the vital transition from a powered-off state to a fully functional system.</p><h4><strong>Boot Devices</strong></h4><p>Boot devices are specific hardware components that contain the necessary software to initiate the booting process. These devices, such as hard drives, SSDs, optical drives, or USB drives, store the operating system or boot loader essential for system startup.</p><h4>BIOS</h4><p>BIOS stands for <strong>Basic Input/Output System</strong>, and is software that starts a computer’s system after it is turned on. It is stored on a small memory chip on the motherboard, and is the first software to run when a computer is started.</p><p>BIOS is a firmware.</p><h4>UEFI</h4><p><strong>Unified Extensible Firmware Interface</strong> (UEFI) is a firmware interface that controls the booting process of a PC. It replaced the standard basic input/output system (BIOS) with new features like faster startup and improved security. UEFI is newer and offers more features and benefits than BIOS</p><h4><strong>Firmware</strong></h4><p>Firmware is software that is written to a hardware device’s memory. It is used to run user programs on said devices.</p><p>Firmware is a type of software that is <strong><em>embedded into hardware devices</em></strong> to control their functionality. Unlike traditional software, <strong>firmware is not designed to be modified or updated frequently, and it is typically stored in non-volatile memory.</strong> It serves as a bridge between the hardware and software layers of a system, allowing the hardware to interact with the operating system and applications.</p><blockquote>The firmware’s purpose is to manage specific hardware components. As a result, these are single-purpose codes designed to control a single device.</blockquote><p>Furthermore, firmware can act as an operating system for simple and less sophisticated systems. Firmware can carry out simple operations and contains low-level programming algorithms. Additionally, it’s limited to controlling specific hardware parts. Every piece of hardware may have a unique set of unaltered codes.</p><h4>Device Drivers</h4><p>A <strong><em>driver</em> </strong>is a software component that lets the operating system and a device communicate. For example, when an app needs to read data from a device, it calls a function implemented by the operating system. The operating system then calls a function implemented by the driver. The driver, usually developed by the device’s manufacturer, knows how to communicate with the device hardware to get the data. Once the driver gets the data, it gives it back to the operating system, which then gives it back to the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*svcCW5lvHF2vBQhllGSZzw.png" /><figcaption><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/what-is-a-driver-">src</a></figcaption></figure><h3><strong>Booting Process</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*2taeFTFB2KZmabutxkhH_A.png" /><figcaption><a href="https://gyires.inf.unideb.hu/GyBITT/20/ch02s02.html">src</a></figcaption></figure><h4>Step 1: Power ON</h4><h4>Step 2: BIOS/UEFI</h4><p>It runs checks on all the hardware components and prepares them for use by the higher level software. These firmware typically resides in a computer chip and not on your hard drive. It is not part of the Operating System. It does not care if you are booting Linux, Windows, or mac OS.</p><p><strong>Step 2.1</strong></p><ul><li><strong>POST — </strong>Power On Self Test</li></ul><blockquote>In order to check the operability of all the hardware connected to our computer system, BIOS carries out POST which will check the hardware components and if any problem is found user is alerted with POST beeps and POST screen messaged.</blockquote><p><strong>Step 2.2</strong></p><ul><li>These firmware loads the MBR by checking the bootable devices.</li></ul><blockquote>If a system is configured to support dual booting (the ability to choose from more than one OS), it is the boot managers that provides this capability to select particular OS(bootable device) and start booting by passing the control to MBR(specific to selected OS) from Boot manager(BIOS/UEFI)</blockquote><p>With BIOS, it simply loads and executes the first sector off the disk it decides to boot from, which typically is the first hard disk detected. By convention the first sector of a hard disk, called the Master Boot Record</p><p>If MBR is not found in any of them, the system will halt by displaying “No Boot Device Found”.</p><h4>Step 3: MBR</h4><p><strong>Master Boot Record</strong> — 1st Stage bootloader</p><p>Once the <strong>BIOS</strong> is done doing whatever initialization that it needs to do, it starts the loading process from the system boot device, usually your first hard disk. The first thing that loads is a tiny<strong> 512 bytes</strong> program called the Master Boot Record (MBR). This program lives in the first sector of your hard drive, and its only job is to determine the bootable partition, and load and execute the first sector of that partition(active partition) (the stage 1 bootloader).</p><p>Simply,</p><p>The program in the boot-sector is loaded in memory (1st stage). This tiny program has information which programs should it load into memory next and where that program is located in Disk or Boot device.</p><p>Step by step process</p><ul><li><strong>Read MBR</strong>: The BIOS or UEFI firmware reads the first sector (512 bytes) of the selected storage device(OS file) into memory. This sector contains the MBR.</li><li><strong>Boot Code Execution</strong>: The 512 bytes of the MBR include a small piece of executable code known as the <strong>**boot code**</strong>. This code is executed by the computer’s CPU.</li><li><strong>Partition Table Examination</strong>: The MBR contains a partition table that describes the layout of the disk. The boot code examines this table to identify the active (bootable) partition.</li><li><strong>Loading Boot Loader</strong>: The boot code then loads the boot loader from the active partition. The boot loader is responsible for loading the system programs or the operating system.</li></ul><blockquote>The conventional MBR code checks the MBR’s partition table for a partition set as bootable (the one with active flag set). If an active partition is found, the MBR code loads the boot sector code from that partition, known as Volume Boot Record (VBR), and executes it. The VBR is often operating system specific while the MBR code is not operating system specific.</blockquote><blockquote>In general terms, the MBR code is the first stage boot loader, while the VBR code is the Second-stage boot loader. Second-stage boot loaders, such as GNU GRUB, BOOTMGR, Syslinux, or NTLDR, are not themselves operating systems, but are able to load an operating system properly and transfer execution to it. This is why we said that these codes are operating system specific.</blockquote><p>Parts of the MBR</p><ol><li><strong>Bootstrap Code</strong>: The Bootstrap Code, often referred to as the boot loader code, is the first part of the Master Boot Record (MBR). It occupies the initial 446 bytes of the MBR. This code is crucial in the boot process as it is executed by the computer’s BIOS or UEFI firmware. Its primary function is to locate and load the operating system’s boot loader, which then continues the booting process.</li><li><strong>Partition Table</strong>: The Partition Table is a 64-byte section within the MBR. It follows the Bootstrap Code and precedes the Master Boot Record Signature. The partition table is divided into four 16-byte entries, each describing a specific partition on the storage device. Information includes the starting and ending addresses of the partition, partition type, and a flag indicating if the partition is bootable (active). The partition table is essential for the operating system to understand the layout of the disk and locate individual partitions.</li><li><strong>Master Boot Record Signature</strong>: The Master Boot Record Signature is a 2-byte value located at the very end of the MBR, specifically at bytes 511 and 512. It consists of the hexadecimal values 0x55AA. This signature is a marker that indicates a valid and bootable MBR. During the boot process, the system checks for this signature to ensure the integrity of the MBR. If the signature is present, it signifies a proper MBR structure, and the system proceeds with the booting process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*pPnZhYQ9AU8Nc-zep8kmng.png" /><figcaption><a href="https://www.scaler.com/topics/operating-system/master-boot-record/">src</a></figcaption></figure><h4>Step 4: VBR</h4><p><strong>Volume Boot Record</strong> — 2nd stage bootloader</p><blockquote>such as <strong>GRUB </strong>(used by Linux), <strong>BOOTMGR </strong>(Windows), or <strong>BootX </strong>(macOS).</blockquote><ul><li>Once the MBR Boot code is loaded in the memory and executed the corresponding bootloaders(OS sepcific) will load the kernel image (system files)</li><li><strong>Operating System Initialization</strong>: The loaded boot loader initializes the kernel image, and control is transferred to the kernel of the operating system.</li></ul><h4>Step 5: Kernel</h4><p>After loading the kernel, bootloader turns over execution to it and the kernel initializes the rest of the operating systems.</p><blockquote>Kernel image is also a bin file that gets executed by bootloader. Kernel image formats vary based on compression, architecture, and specific use cases.</blockquote><blockquote>In Ubuntu, the Linux kernel image is located in the folder /boot/. The file name is vmlinuz-5.15.0.76-generic</blockquote><h4>Step 6: init</h4><p>Kernel then calls the init scripts like <strong>SysV </strong>or <strong>Upstart </strong>or <strong>Systemd</strong> (PID 1) to start all other services.</p><p>Resource links:</p><ul><li><a href="https://courses.cs.washington.edu/courses/cse451/02wi/section/bootloaders.txt">https://courses.cs.washington.edu/courses/cse451/02wi/section/bootloaders.txt</a></li><li><a href="https://gyires.inf.unideb.hu/GyBITT/20/ch02s02.html"><strong><em>https://gyires.inf.unideb.hu/GyBITT/20/ch02s02.html</em></strong></a></li><li><a href="https://www.youtube.com/watch?v=XpFsMB6FoOs">https://www.youtube.com/watch?v=XpFsMB6FoOs</a></li><li><a href="https://www.scaler.com/topics/operating-system/what-is-booting/">https://www.scaler.com/topics/operating-system/what-is-booting/</a></li><li><a href="https://www.scaler.com/topics/operating-system/what-is-bios/">https://www.scaler.com/topics/operating-system/what-is-bios/</a></li></ul><p>Hope this post is helpful and educative.</p><p>Happie learning</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b77a61dccc49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenID Connect simplified]]></title>
            <link>https://towardsdev.com/openid-connect-simplified-419cfba6898c?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/419cfba6898c</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[openid-connect]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 02:40:26 GMT</pubDate>
            <atom:updated>2023-01-05T15:06:58.415Z</atom:updated>
            <content:encoded><![CDATA[<p>What is OpenID Connect (or OIDC)? Before moving forward if OAuth2.0 sounds unfamiliar or need to revist the concepts then checkout <a href="https://medium.com/@LogeshSakthivel/oauth2-0-simplified-802ac0d7bfb2">this article</a>.</p><p><strong>OAuth2.0 </strong>is designed only for authorization for granting access to data from one application to another. OAuth is like giving an application (Client) a key(Token). That key is useful but that doesn’t tell the client who you are or anything about you. OpenID Connect (OIDC) is a thin layer that sits on top of OAuth2.0 that adds functionality around login and profile information about the person who is logged in.</p><blockquote>That time when the OAuth2.0 is widely used sometimes OAuth has been used for the Authentication as well but it wasn’t built for that. So, to use OAuth for the authentication as well a standard is built on top of OAuth2.0. OIDC is like an extension to OAuth.</blockquote><h3>OAuth2.0 and OpenID Connect</h3><ul><li>OpenID Connect is for <strong>authentication</strong></li><li>OAuth2.0 is for <strong>authorization</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*eBDOGq5lC3cKtrHH1mpBeg.png" /></figure><p>By using OpenID connect on top of OAuth it gives the standard implementation for authentication using OAuth across vendors so that the interop will be seemless.</p><p>OpenID Connect adds</p><ul><li>ID token (in addition to the access token)</li><li>Userinfo endpoint for getting more user information</li></ul><h4>OpenID Connect authorization code flow</h4><p>We use OAuth request to the Authorization server to do OpenID connect .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtSCkFcRSIPi6hZ2Yx-oXw.png" /><figcaption>OIDC flow</figcaption></figure><p>The OpenID connect will have the scope as <strong>openid </strong>with other scopes based on the requirement. The <strong><em>openid </em></strong>in the scope says the Authorization server to identify this request as the OpenID connect.</p><p>So now we got our access token and ID token for the authorization code.</p><blockquote>The ID Token (Identity Token) is a JWT token that has some user information with it.</blockquote><p>We could also use the access token to get additional user info from the /userinfo endpoint (also do the stuffs that it asked for in the scopes with the access token).</p><p>This way we get to know the user so we could use this standard for the Authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*NxNSomchtkbRZW3AnqUtwQ.png" /></figure><p>Hope this simple article helps you to understand what OpenID connect is.</p><p>Some other resources,</p><ul><li><a href="https://youtu.be/996OiexHze0">https://youtu.be/996OiexHze0</a></li><li><a href="https://developer.okta.com/docs/guides/validate-access-tokens/dotnet/main/">Token validation</a></li><li><a href="https://oauth.net/2/token-revocation/">Token revocation</a></li></ul><p>Happie Learning :)</p><p>Keep Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419cfba6898c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/openid-connect-simplified-419cfba6898c">OpenID Connect simplified</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2.0 simplified]]></title>
            <link>https://towardsdev.com/oauth2-0-simplified-802ac0d7bfb2?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/802ac0d7bfb2</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[oauth-flow]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 02:55:22 GMT</pubDate>
            <atom:updated>2023-01-04T15:00:46.584Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started learning OAuth it became overwhelmed by all the strange terminology and jargon. So i decided to write this article for someone who is trying to get start with the OAuth2.0 as a newbie.</p><blockquote>Throughout this article we will cover OAuth2.0, so moving forward if you see me mentioning OAuth it refers to OAuth2.0</blockquote><p>In this article we will cover,</p><ul><li>need for OAuth2.0 (what problem does OAuth solves)</li><li>OAuth and its terminologies</li><li>OAuth flow</li></ul><h4>Need for OAuth2.0</h4><p>In the old days, if an App used by the user needs to access/share some information of other services used by that user then simply the user needs to provide the username and password of the service to the App that it needs. (This is basically trusting that App which shouldn’t be)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*wb_uDIR9WuUW-Gr-o_hJjg.png" /><figcaption>Golden old days of accesing other services</figcaption></figure><p>Ex: If <strong>MyApp </strong>application used by <strong>Bob </strong>and that App needs to access the Bob’s <strong>Google contacts</strong>, then MyApp will get the Bob’s username and password for his Google account and use the Google Contacts API to get the Bob’s contacts. In this scenario, Bob needs to trust the MyApp that they won’t misuse the credentials.</p><p>Here, OAuth came to resolve this. At the high level, instead of getting the user’s other services credential <strong>OAuth </strong>lets the App to redirect the user to that service and make them to login to that respective service domain and then get the access token to access that service by the App.</p><h4>OAuth and its Terminologies</h4><blockquote>OAuth is an open standard for access delegation, commonly used as a way for internet users to grant websites or applications access to their information on other websites but without giving them the passwords. — <a href="https://en.wikipedia.org/wiki/OAuth">Wikipedia</a></blockquote><p>Simply, OAuth2.0 is a security standard (mainly for authorization) where user give one application permission to access user’s data in another application instead of giving them username and password, user can give one app a key that gives them a specific permission to access user’s data in another application.</p><p>In OAuth, you authorize one application to access your data in another application.</p><p>Terminologies:</p><ul><li><strong><em>Resource owner</em></strong> — Mostly its the user or the owner of the data which is need to be accessed. In our example its <strong>Bob</strong>.</li><li><strong><em>Client </em></strong>— The Application/Service which needs to access the user data. In our example its <strong>MyAPP</strong></li><li><strong><em>Authorization server</em></strong> — The Application that knows the resource owner where the resource owner already has an account. In our example its <strong>Google.</strong></li><li><strong><em>Resource server</em></strong> — The API or service the client wants to use on behalf of the resource owner. Sometimes the Authorization server and the Resource server are the same. In our example its <strong>Google Contacts API.</strong></li><li><strong><em>Redirect URI </em></strong>— This is the URL the authorization server will redirect the resource owner back to, after granting permission to the client. Sometimes referred to as the callback URL.</li><li><strong><em>Response type </em></strong>— The type of information the client expects to receive. The most common response type is <strong>code </strong>where the client expects to receive an authorization code.</li><li><strong><em>Scope </em></strong>— These are the granular permissions the client wants such as access to data or to perform actions.</li><li><strong><em>Consent </em></strong>— The Authorization server takes the scopes the Client is requesting and verifies with the resource owner whether or not they want to give the client permission.</li><li><strong><em>Client ID </em></strong>— This ID is used to identify the Client with the authorization server.</li><li><strong><em>Client Secret </em></strong>— This is the secret password that only the client and the authorization server know, this allows them to securely share informations. (The Client ID and the Client secret needs to be generated by the Authorization server for the Client, kindoff manual work the dev of the Client need to do)</li></ul><blockquote>Client ID and Client secret were issued to the client during the Application registration process with the Authorization server.</blockquote><ul><li><strong><em>Authorization code</em></strong> — This is a short lived temporary code the authorization server sends back to the client. The Client then privately sends the authorization code back to the Authorization server along with the client secret in exchange for an access token.</li><li><strong><em>Access token </em></strong>— is the key, the client will use from that point forward to communicate with the resource server. Mostly of JWT tokens.</li></ul><p>Some more terminologies to know</p><ul><li><strong><em>Back channel </em></strong>— Highly secure channel (the communication which is highly secure). Example, the code that is running on your own server and communicating with other server.</li><li><strong><em>Front channel </em></strong>— Less secure channel (the communication that is least secure). Example, the web app in the browser communicating with the other servers. There is no issue in this scenario but what if the client secret is embedded inside the webapp and the browser is built in a way that any one can see the front end source code by inspecting the elements in the browser.</li></ul><h4>OAuth Flow</h4><p>OAuth2.0 provides several “grant types” for different use cases.</p><ul><li><strong>Authorization Code </strong>(Front channel + Back channel)</li><li><strong>Implicit </strong>(Front channel only)</li><li><strong>Password Credentials </strong>(Back channel only)</li><li><strong>Client Credentials </strong>(Back channel only)</li></ul><h4>OAuth2.0 Authorization code flow</h4><p><strong>Bob </strong>(Resource owner) wants to allow the <strong>MyApp</strong>(Client) to access his Google contacts.</p><p>The Client redirects Bob’s browser to the <strong>Authorization Server </strong>(Google)and includes with the request the <strong>Client ID, Redirect URI, Response type </strong>and one or more <strong>Scopes </strong>it needs.</p><p>The Authorization server verifies Bob and if necessary it prompts for Login.</p><p>The Authorization server then presents the Bob with the <strong>Consents </strong>whether or not to allow the Client with the listed scopes of access. The Bob can allow or deny the permissions.</p><p>The Authorization Server redirects back to the Client using the redirect URI along with a temporary <strong>authorization code.</strong></p><p>The Client then requests the Authorization server directly (it does not use the Bob’s browser) and securely sends its Client ID, <strong>Client Secret </strong>and the authorization code.</p><p>The Authorization server verifies the data and responds with an <strong>Access token.</strong></p><p>The Client can use the access token to send requests to the <strong>Resource server </strong>and the Resource server verifies the access token and if valid responds with the response for that request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBOFdXbdDXu6-o-fVPhXLA.png" /><figcaption>OAuth2.0 Authorization code flow</figcaption></figure><p>The communication that happens in the Front channel is done by using the Bob’s browser. And in the Back channel it happens by the Client’s server (or the Client’s backend)</p><p>Why do we need to send the Authorization code and then the Client uses that to get the Access token?</p><p>Its mainly because when the Client is requesting the data from the Resource server it needs to send the access token with the Client Secret, so we can’t embed our Client Secret in the webapp due to the security issue and what if the attacker intercepts the communication in the front channel and gets the Access token which is also a security issue. So we made the Authorization server to return the Authorization code in the front channel and then the Client gets the Access token for that Authorization code in the back channel (<strong>Authorization Code </strong>grant type).</p><h4>OAuth2.0 Implicit flow</h4><p>In the <strong>Implicit flow </strong>grant type there is no back channel (or backend), we only have the frontend webapp so in this case the Authorization server will return back the Access token instead of the Authorization code. Here the security tradeoff occured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMpE2RUj_pCwTmOmfOKH0A.png" /><figcaption>OAuth2.0 Implicit flow</figcaption></figure><p>In the <strong>Password Credentials </strong>and the <strong>Client Credentials </strong>there is no front channel, which means there is no user interaction or they don’t involve users browser at all. These flows are mainly for the machine to machine (service to service) communications.</p><p>Hopefully, I guess this article might introduces you with the OAuth2.0 and there is much more to learn about this standard here I will provide the link to some of the useful resources.</p><ul><li><a href="https://www.oauth.com/">OAuth.com</a></li><li><a href="https://oauth2simplified.com/">OAuth2simplified</a></li><li><a href="https://youtu.be/t18YB3xDfXI">https://youtu.be/t18YB3xDfXI</a></li><li><a href="https://developer.okta.com/blog/">Okta Blogs</a></li></ul><p>Happie Learning :)</p><p>Keep Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=802ac0d7bfb2" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/oauth2-0-simplified-802ac0d7bfb2">OAuth2.0 simplified</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Webapp with Flet and Telegram bot]]></title>
            <link>https://towardsdev.com/simple-webapp-with-flet-and-telegram-bot-219dba692363?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/219dba692363</guid>
            <category><![CDATA[flet]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 14:53:56 GMT</pubDate>
            <atom:updated>2022-12-15T21:06:19.784Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will build a simple webapp (Leave me a message app) using Flet in Python and use the Telegram bot to send the user submitted information.</p><blockquote>This <a href="https://leavemeamessage.logeshsakthivel.repl.co/">Leave me a message</a> project is live at Repl. So you guys could leave me a message that you have for me☺️.</blockquote><h3>High Level Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*6NHZP30YZeErkWHbEoc7NQ.png" /><figcaption>High level overview of the Project</figcaption></figure><p>Whenever the user fills the form and press submit, the telegram bot that I have created will take those information and notifies me in the Telegram.</p><blockquote>This Webapp is very minimal and my motto is to get start with Flet in Python.</blockquote><p>If Flet sounds unfamiliar to you please do take a look at this <a href="https://medium.com/@LogeshSakthivel/flutter-apps-in-python-flet-3fccdaabc34f">article</a>.</p><h4>Web App</h4><p>Once the flet module is installed, we are ready to build our App.</p><p>The UI, we will be building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*MzqEaLLqunALnFfj" /><figcaption>Leave me a message webapp</figcaption></figure><p>The boilerplate code</p><pre>import flet as ft<br><br><br>def main(page: ft.Page):<br>    page.title = &quot;Contact Logesh&quot;<br>    page.theme_mode = ft.ThemeMode.LIGHT # have used light theme<br>    # align the controls of the page to the Center<br>    page.vertical_alignment = ft.MainAxisAlignment.CENTER<br>    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER<br><br><br>ft.app(target=main, view=ft.WEB_BROWSER)</pre><p>Adding appbar</p><pre>main_appbar = ft.AppBar(<br>        title=ft.Text(&quot;Leave me a message&quot;, style=ft.TextThemeStyle.TITLE_LARGE),<br>        center_title=True,<br>        bgcolor=ft.colors.BLUE_GREY_50,<br>    )<br>page.appbar = main_appbar</pre><p>Now, adding the controls</p><pre>def get_textfield(label_str, is_email=False):<br>    # captitalize the sentence.<br>    text_cap = ft.TextCapitalization.SENTENCES<br>    if is_email:<br>        # if the text field is for email, then no capitalization<br>        text_cap = ft.TextCapitalization.NONE<br>    return ft.TextField(label=label_str, border=ft.InputBorder.NONE, filled=True, cursor_color=ft.colors.BLACK38,<br>                             label_style=ft.TextStyle(color=ft.colors.BLACK38), capitalization=text_cap)<br><br># textfields<br>name_text = get_textfield(&quot;Your Name&quot;)<br>mail_text = get_textfield(&quot;Email id&quot;, True)<br>msg_text = get_textfield(&quot;Your Message/Query&quot;)<br><br># submit button<br>def button_clicked(e):<br>    # need to implement<br>    pass<br><br># button_clicked function takes the event as a parameter.<br>b = ft.ElevatedButton(text=&quot;Submit&quot;, on_click=button_clicked, color=ft.colors.BLACK, style=ft.ButtonStyle(<br>        color=ft.colors.BLACK,<br>        overlay_color=ft.colors.BLUE_GREY_50<br>    ))</pre><p>Now that we have our controls but we need to format them in a way we need.</p><pre># button is placed inside the row control<br>row = ft.Row(<br>        controls=[b],<br>        alignment=ft.MainAxisAlignment.CENTER<br>    )<br><br># added the text fields and the row to the column control<br>col1 = ft.Column(<br>        controls=[name_text, mail_text, msg_text, row],<br>        alignment=ft.MainAxisAlignment.SPACE_AROUND,<br>    )<br><br><br># now placed the column control inside a container<br>con1 = ft.Container(<br>        content=col1,<br>        alignment=ft.alignment.center,<br>        padding=10,<br>        width=500,<br>        height=350,<br>        border_radius=10,<br>        ink=True,<br>        bgcolor=ft.colors.WHITE54<br>    )<br><br># add the container to the page control<br>page.add(con1)<br></pre><p>Now implementing the button_clicked method.</p><pre>def button_clicked(e):<br>    # we need to add null check for the text fields<br>    # check for the empty string for the textfield value. <br>    # If its empty then make the error_text for that textfield to say that this field is mandatory<br>    # note: page.update() is necessary.<br>    is_null = False<br>    if name_text.value == &quot;&quot;:<br>        is_null = True<br>        name_text.error_text = &quot;Please enter your name&quot;<br>    if msg_text.value == &quot;&quot;:<br>        is_null = True<br>        msg_text.error_text = &quot;Please enter some message :(&quot;<br>    if mail_text.value == &quot;&quot;:<br>        is_null = True<br>        mail_text.error_text = &quot;Please enter your email id&quot;<br>    page.update()<br>    if not is_null:<br>        # if all the info is typed then structure the info, so that bot will notify me in Telegram<br>        msg_to_send = f&quot;{name_text.value}\n{mail_text.value}\n\n{msg_text.value}&quot;<br>        # Telegram bot code will be inserted here to send the formatted message.<br>        # make the textfield values to empty and the error text to None.<br>        name_text.value = &quot;&quot;<br>        msg_text.value = &quot;&quot;<br>        mail_text.value = &quot;&quot;<br>        name_text.error_text = None<br>        msg_text.error_text = None<br>        mail_text.error_text = None<br>        # now append new view to the page. which is the success page<br>        page.views.append(<br>                ft.View(<br>                    &quot;/done&quot;,<br>                    [<br>                        ft.AppBar(title=ft.Text(&quot;Message Sent&quot;, style=ft.TextThemeStyle.TITLE_LARGE),<br>                                  bgcolor=ft.colors.SURFACE_VARIANT, center_title=True, ),<br>                        ft.Text(&quot;Thanks for leaving a message :)&quot;, style=ft.TextThemeStyle.DISPLAY_SMALL),<br>                        ft.Text(&quot;Will be in touch soon...&quot;, style=ft.TextThemeStyle.TITLE_MEDIUM),<br>                    ],<br>                    horizontal_alignment=ft.CrossAxisAlignment.CENTER,<br>                    vertical_alignment=ft.MainAxisAlignment.CENTER<br>                )<br>            )<br>        # see the change in UI<br>        page.update()</pre><p>Lot of logics goes into the button_clicked method. Simply put when the user clicks submit button this method,</p><ul><li>checks for the empty value for the textfields.</li><li>if empty, give error_text else form a string using the entered details and make the Telegram bot to send this msg to the chat that we specify (I will explain the Telegram part later in its own section).</li><li>revert the error_text and the value of the textfileds to default.</li><li>append the new view to the Page which indicates the success of the user submission.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wg_ZG_G_uohADAKEi-yNcA.png" /><figcaption><a href="https://flet.dev/docs/guides/python/navigation-and-routing">https://flet.dev/docs/guides/python/navigation-and-routing</a></figcaption></figure><p>To know more about the Page Views checkout the <a href="https://flet.dev/docs/guides/python/navigation-and-routing#page-views">official Flet doc</a>.</p><p>The User can go back to the form page from the success page. That can be done by using the <strong>page.views.pop()</strong></p><pre>def view_pop(view):<br>    # pops the current view<br>    page.views.pop()<br>    # now get the last view then route to that view<br>    top_view = page.views[-1]<br>    page.go(top_view.route)<br><br># on_view_pop of the Page takes the function that is called when the back button is pressed<br>page.on_view_pop = view_pop</pre><h3>Telegram Bot</h3><h4>Create a Bot</h4><ul><li>Open the Telegram and search for <strong>BotFather</strong></li></ul><p>Make sure to select the verified one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*z_Z-TP1BmTJSe7GLFtbOsw.png" /><figcaption>Verified BotFather</figcaption></figure><p>Start the chat with BotFather by the command <strong>/start </strong>it will list the available commands. Our focus is to create the Bot so, send the command <strong>/newbot</strong></p><p>It will asks for the Bot name, give a name for your Bot.</p><p>Now, it will asks to create the username for your bot. Give a username for your Bot.</p><p>Upon success it will provide you a Bot Access Token. (never share that) This is the Token we will be using to control our Bot.</p><p>At this point we are ready with our Bot Token, now moving to find the chat id where the bot will send the message.</p><p>If you wish to make this Bot to send the messages to you then provide your chat id else if you wish to create a group with the Bot then provide the Group chat id.</p><h4>Finding chat id</h4><p>To find the chat id of yours enter the below url (by replacing &lt;BOT_TOKEN&gt; with your bot token) in the browser and then send the message to the Bot and refresh the browser you could see the chat details in the JSON format, find the ID there. Thats your chat id.</p><pre>https://api.telegram.org/bot&lt;BOT_TOKEN&gt;/getUpdates?offset=0</pre><p>To find the Group chat ID(or Group ID) where you and your Bot were the participants of that group, do the same as above but instead of sending the message to the Bot chat send the message in the Group. Refresh the browser you could see your message details there you could find the Group ID.</p><p>Now we got our Chat ID.</p><h4>Sending message</h4><pre># telegram_bot.py<br>import requests<br>TOKEN = &quot;YOUR_BOT_TOKEN&quot;<br>bot_msg_snd_url = f&quot;https://api.telegram.org/bot{TOKEN}/sendMessage&quot;<br><br><br>def send_msg(msg):<br>    params = {&quot;chat_id&quot;: &quot;&lt;CHAT_ID&gt;&quot;, &quot;text&quot;: str(msg)}<br>    resp = requests.get(bot_msg_snd_url, data=params)<br>    if resp.json()[&quot;ok&quot;]:<br>        print(&quot;Successfully sent the msg&quot;)<br>    else:<br>        print(&quot;Failed to sent the msg&quot;)</pre><p>This is the simple function that sends the message to the chat by the Bot we specify.</p><p>Calling this function in our button_clicked method.</p><pre># main.py<br>import telegram_bot<br><br>def button_clicked(e):<br>    # ...<br>    # ...<br>    if not is_null:<br>        # send msg<br>        telegram_bot.send_msg(msg_to_send)<br>        # ...</pre><p>Almost we came to the end of our project.</p><p>Updating the loading animation image and Webapp favicon icon.</p><p>Create assets dir under the Project root dir and place the <strong>favicon.png</strong> there and create icons dir under assets dir and place the <strong>loading-animation.png </strong>there with the same name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*z43RkUGOfu4MUeAY50eY4g.png" /><figcaption>assets folder structure</figcaption></figure><p>And make the flet app to know about the assest dir.</p><pre>ft.app(target=main, assets_dir=&quot;assets&quot;, view=ft.WEB_BROWSER)</pre><p>Also, we can make the custom manifest.json file. <a href="https://github.com/flet-dev/examples/blob/main/python/apps/custom-loading-image/assets/manifest.json">Example</a></p><p>All set, we are ready with our Webapp.</p><p>Checkout the doc for <a href="https://flet.dev/docs/guides/python/deploying-web-app">deploying the Flet App</a>.</p><h3>Demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9S0AdPnXNAViwSHdTwTO1A.png" /><figcaption><a href="https://leavemeamessage.logeshsakthivel.repl.co/">https://leavemeamessage.logeshsakthivel.repl.co/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*BnJ8FHaeyg7ZUMpa2LsFZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*5SlsMfmziIFuQ8KqwsWX2A.png" /><figcaption>success page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*HOamkqK00m--rdeiJ3MHlw.png" /><figcaption>Bot Message</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*tHO9lzp4CHyz7MCDdzyNcA.png" /><figcaption>textfield error_text</figcaption></figure><p>For the source code checkout <a href="https://github.com/LogeshVel/leave_me_a_message">my Github repo</a>. Hope you find this article useful.</p><p>Happie Learning :)</p><p>Keep Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219dba692363" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/simple-webapp-with-flet-and-telegram-bot-219dba692363">Simple Webapp with Flet and Telegram bot</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter apps in Python — Flet]]></title>
            <link>https://towardsdev.com/flutter-apps-in-python-flet-3fccdaabc34f?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fccdaabc34f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flet]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 13:03:18 GMT</pubDate>
            <atom:updated>2022-12-14T16:51:59.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter apps in Python — Flet</h3><blockquote>Flet is a framework that allows building interactive multi-user web, desktop and mobile applications in your favorite language. You build a UI for your program with Flet controls which are based on Flutter by Google. Flet does not just “wrap” Flutter widgets, but adds its own “opinion” by combining smaller widgets, hiding complexities, implementing UI best-practices, applying reasonable defaults. At the moment you can write Flet apps in Python. — <a href="https://flet.dev/docs/">flet</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOJF7uhnSSGzrE8UjD0GCg.png" /><figcaption><a href="https://flet.dev/">https://flet.dev/</a></figcaption></figure><h3>Flet module</h3><pre>pip install flet</pre><blockquote>Installation specific to <a href="https://flet.dev/docs/guides/python/getting-started/#linux">Linux and WSL</a>.</blockquote><p>After installing the module we could simply import flet and start building our App.</p><h3>Getting started</h3><h4>Hello world</h4><p>The simple Hello World! app would look like,</p><pre>import flet as ft<br><br><br>def main(page: ft.Page):<br>    page.title = &quot;Hello world App&quot;<br>    page.add(ft.Text(&quot;Hello, Flet World!&quot;))<br><br><br>ft.app(target=main)</pre><p>The app will be started in a native OS window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*js_DZk0dC94xDmYxNz0ujA.png" /><figcaption>Windows app</figcaption></figure><p>If you want to run the app as a web app, then</p><pre>ft.app(target=main, view=ft.WEB_BROWSER)</pre><h3>Controls</h3><blockquote>User interface is made of Controls (aka widgets). To make controls visible to a user they must be added to a Page or inside other controls. Page is the top-most control. Nesting controls into each other could be represented as a tree with Page as a root.</blockquote><blockquote>Controls are just regular Python classes. Create control instances via constructors with parameters matching their properties. — <a href="https://flet.dev/docs/guides/python/getting-started/#controls">flet controls</a></blockquote><p>Controls in our Hello world code</p><pre>t = ft.Text(&quot;Hello World!&quot;)</pre><p>To display the controls on the page that we defined, we need to append it to the Page controls and update the page.</p><pre>page.controls.append(t)<br>page.update()</pre><p>But luckily we have page.add() which does the same.</p><pre>page.add(t)</pre><p>Whenever we made change to the controls, we need to use page.update() method to see the changes in the UI.</p><p>Example of changing the value of the text.</p><pre>import flet as ft<br>from time import sleep<br><br><br>def main(page: ft.Page):<br>    t = ft.Text()<br>    page.add(t)  # it&#39;s a shortcut for page.controls.append(t) and then page.update()<br><br>    for i in range(10):<br>        t.value = f&quot;Step {i}&quot;<br>        page.update() # updating the change<br>        sleep(1)<br><br><br>ft.app(target=main)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*669viisY22yTKo869vgMlg.png" /><figcaption>Step incremented from 0 to 9</figcaption></figure><p>Whatif the page.update() is removed, simply the change that we made to the text won’t be reflected in the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*587mCe61q-b09QTdE4ZLcA.png" /><figcaption>UI when the page.update() is removed</figcaption></figure><p>Flet almost has all the Flutter widgets in the name of <strong>Controls</strong>.</p><h3>Next step</h3><p>So far we have seen the introduction to Flutter Apps in Python using Flet framework, as a next step I will attach the links to the Flet docs to get to know more about Flet.</p><ul><li><a href="https://flet.dev/docs/guides/python/getting-started">Flet apps in Python</a></li><li><a href="https://flet.dev/docs/controls">Flet Controls</a></li><li><a href="https://flet.dev/docs/tutorials/python-todo">To-Do app in Python with Flet</a></li><li><a href="https://flet.dev/docs/tutorials/python-calculator">Python Calculator app</a></li><li><a href="https://flet.dev/docs/roadmap">Flet Roadmap</a></li></ul><p>At the time of writing this article, the Flet doesn’t supports standalone Mobile apps. It uses <a href="https://flet.dev/docs/guides/python/mobile-support">Server-driven UI</a> (SDUI).</p><p>Hope this article introduces you with the Flet.</p><p>Happie Flet!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fccdaabc34f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/flutter-apps-in-python-flet-3fccdaabc34f">Flutter apps in Python — Flet</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More on Go routines]]></title>
            <link>https://towardsdev.com/more-on-go-routines-a875fc0cc9a1?source=rss-40271b79ac98------2</link>
            <guid isPermaLink="false">https://medium.com/p/a875fc0cc9a1</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[deadlock]]></category>
            <dc:creator><![CDATA[Logesh]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 14:31:41 GMT</pubDate>
            <atom:updated>2022-10-07T12:58:46.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Achieve Concurrency using Go routine in Golang.</p><p>Concurrency is great but we might get some problems as a byproduct. Here we will look into some of the problems and how to handle the same. Also, we cover some of the concepts involved/used in Go routines.</p><h3>Early Exit</h3><p>When the main goroutine completes all other goroutines will exits.</p><p>A Goroutine may not complete its execution because main goroutine completes early.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76c52f13a39a55b1cd86bbb1318c2fb2/href">https://medium.com/media/76c52f13a39a55b1cd86bbb1318c2fb2/href</a></iframe><h4>Solution</h4><p>Either we can use the Go <strong>channels</strong>(but it can also used to communicate between Goroutines) or <strong>WaitGroup </strong>method of the sync package.</p><p><strong>Using channel</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac99f01e97d333a9c2feb1828764791/href">https://medium.com/media/4ac99f01e97d333a9c2feb1828764791/href</a></iframe><ul><li>Here we just made the main goroutine to wait until we receive the value from the channel c. We could receive the value from the channel only if the value is sent to the channel. We are sending the value to the channel in another go routine, so the main go routine is blocked until the value is received from the channel.</li></ul><p><strong>Using sync.WaitGroup</strong></p><p>Sync package contains functions to synchronize between goroutines.</p><p>sync.WaitGroup forces a goroutine to wait for other goroutine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc12ca1e3d4e357972775393d36cc36/href">https://medium.com/media/bcc12ca1e3d4e357972775393d36cc36/href</a></iframe><h3>Communication between Goroutines</h3><p>Goroutines usually work together to perform a bigger task. So, there must be way to communicate between them. Golang has channels for this.</p><h4>Channels</h4><ul><li>Transfer data between goroutines</li><li>Channels are typed.</li><li>Using make() function we could create a channel.</li></ul><pre>c := make(<strong>chan </strong>string) // channel is typed</pre><ul><li>We could send and receive data using this <strong>&lt;- </strong>operator.</li><li>Send data on a channel</li></ul><pre>c <strong>&lt;-</strong> “Data”</pre><ul><li>Receive data from a channel</li></ul><pre>v := <strong>&lt;-</strong> c</pre><p>We have already seen the example for the channel in the Early exit solution using channel.</p><h4>Types of channel</h4><ul><li>Unbuffered channel(Default)</li><li>Buffered channel</li></ul><h4>Unbuffered channel</h4><p>Channels can contain a limited number of objects. Default size is 0 (no capacity to hold data). Which means it never hold the data, once the data is sent to the channel it can be recieved but it cannot hold(store).</p><h4>Buffered Channel</h4><p>Buffered channel has a capacity to store messages inside it.</p><p>The optional argument to the make() function defines the channel capacity.</p><pre>c := make(chan int, <strong>3</strong>)</pre><p>Now the channel <strong>c</strong> can store 3 objects in it. Sending data to the channel is blocked only when the buffer is full and receiving data from the channel is blocked only when the buffer is empty.</p><h3>Goroutines sharing resources</h3><p>Sharing variables concurrently can cause problems.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04aea6ed4d5ef71b5621c144abe1846d/href">https://medium.com/media/04aea6ed4d5ef71b5621c144abe1846d/href</a></iframe><p>While running this code with the -race flag we could find that the data race is occured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*-kJQe_FoFXVzdfcM7ALBKQ.png" /><figcaption>go run -race sharing_var_prob.go</figcaption></figure><p>In the above snap we could see that,</p><ul><li>Goroutine 7 is created at the line 18 and 8 is created at the line 20</li><li>Data race is occured at the line 12, when the Goroutine 8 tries to read the value which has been modified by the Goroutine 7.</li></ul><h4>Possible interleavings we might thought</h4><blockquote>Concurrency is done by context switching(interleavings). Since in concurrency only one task is executed at a given point of time but they use context switching to switch the flow from one process/thread to another.</blockquote><ul><li>The order of execution between the concurrent tasks is unknown.</li><li>Interleaving of instructions between tasks is unknown.</li></ul><p>So for the above example the possible interleavings can be,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Knw-EnC0bhiu12nFzGCpRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*eX78XNv1ibClNxd2ELJO4Q.png" /></figure><p>From the above snaps we could conclude that at the end its going to be the same output. Before concluding that let me revisit the output of our example.</p><pre>PS E:\_GOlang\go_programs&gt; go run -race .\sharing_var_prob.go<br>==================<br>WARNING: DATA RACE<br><strong>Read at 0x000000638610 by goroutine 8</strong>:<br>  main.Inc()<br>      E:/_GOlang/go_programs/sharing_var_prob.go:12 +0x29</pre><pre><strong>Previous write at 0x000000638610 by goroutine 7</strong>:<br>  main.Inc()<br>      E:/_GOlang/go_programs/sharing_var_prob.go:12 +0x44</pre><pre>Goroutine 8 (running) created at:<br>  main.main()<br>      E:/_GOlang/go_programs/sharing_var_prob.go:20 +0x64</pre><pre>Goroutine 7 (finished) created at:<br>  main.main()<br>      E:/_GOlang/go_programs/sharing_var_prob.go:18 +0x44<br>==================<br>2<br>Found 1 data race(s)<br>exit status 66</pre><p>So if you notice the highlighted text we could see that Data race occurs while reading the value of i. But the possible interleavings we discussed has no read operation at a given time. So, Interleavings happens at the machine code level.</p><blockquote>Concurrency is at the machine code level</blockquote><p>i = i + 1 might be three machine instructions.</p><pre>read i<br>increment by 1<br>write i</pre><p>Interleaving at the machine instructions causes unexpected problems.</p><p>We have 6 machine instructions so we could comeup with lot of possible interleavings (since interleavings are not deterministic)</p><h4>Mutual Exclusion</h4><p>Code segments in different goroutines which cannot execute concurrently.</p><p>In Golang to accomplish this we have sync.Mutex</p><h4>sync.Mutex</h4><p>A Mutex ensures mutual exclusion. It uses a binary semaphore.</p><p>Flag up (1)— Shared variable is in use</p><p>Flag down(0) — Shared variable is available</p><h4>sync.Mutex methods</h4><p><strong>Lock() </strong>method puts the flag up (shared variable in use)</p><p>If lock is already taken by a goroutine then Lock() blocks until the flag is put down(unlock)</p><p><strong>Unlock() </strong>method puts the flag down (done using the shared variable)</p><p>When Unlock() is called, a blocked Lock() can proceed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f34975d84df351e7927ea927cb5019a4/href">https://medium.com/media/f34975d84df351e7927ea927cb5019a4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*XwHBD34VmjQG_06XaXhLBw.png" /><figcaption>no data race after using Mutex</figcaption></figure><h3>Synchronous Init (Once synchronization)</h3><p>There might be scenario where function1 calls function2 but function1 is called by multiple go routines but the function2 should be called only once inside the function1.</p><p>Ex:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecb2c7a49b45ce8140c605d0412b3d82/href">https://medium.com/media/ecb2c7a49b45ce8140c605d0412b3d82/href</a></iframe><p>In the output we could see that the setup function is called twice by different go routines. But in our scenario we need to call the setup function only once even though multiple go routines call that function.</p><h4>sync.Once</h4><p>The above problem can be solved by using <strong>sync.Once</strong></p><p>It has a method <strong>Do(f)</strong></p><p>The Function <strong>f </strong>is executed only one time even if it is called in multiple go routines. All calls to the <strong>Do() </strong>method is blocked until the first call returns.(Ensures that intialization executes first)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a66417ea4f696d5d58bee23d1df6ca27/href">https://medium.com/media/a66417ea4f696d5d58bee23d1df6ca27/href</a></iframe><p>From the output we could see that the setup function is executed only once.</p><h3>Deadlock</h3><h4>Synchronization Dependencies</h4><p>Synchronization cause the execution of different goroutines to depend on each other.</p><p><strong>Circular dependencies</strong> cause all involved goroutines to block. It can be caused by waiting on channels.</p><p>Below is the example code for deadlock.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78bb125e6a3194e0e621bdb932c1a80/href">https://medium.com/media/a78bb125e6a3194e0e621bdb932c1a80/href</a></iframe><p>In the above code the <strong>ReceiveAndSend </strong>function tries to receive value from one channel and send value to another channel.</p><p>When the first goroutine runs it waits after the print statement to recieve the value from the channel 1. While waiting, the second goroutine runs and it also waits to receive the value from the channel 2 after the print statement. Either of the goroutine should complete inorder to proceed to the next goroutine. But unfortunately neither of the goroutines completes.</p><p>Golang runtime automatically detects when all the goroutines are deadlocked.</p><blockquote>Note: Deadlock cannot detected when the subset of goroutines are deadlocked</blockquote><p>When we execute this code we will get the go runtime error.</p><pre>Receiving value from channel 1<br>Receiving value from channel 1<br>fatal error: all goroutines are asleep - <strong>deadlock</strong>!<br><br>goroutine 1 [semacquire]:<br><strong>sync.runtime_Semacquire</strong>(0xc0000aa030?)<br>	/usr/local/go-faketime/src/runtime/sema.go:62 +0x25<br>sync.(*WaitGroup).Wait(0x0?)<br>	/usr/local/go-faketime/src/sync/waitgroup.go:139 +0x52<br>main.main()<br>	/tmp/sandbox143763375/prog.go:25 +0x111<br><br><strong>goroutine 18 [chan receive]:</strong><br>main.ReceiveAndSend(0x0?, 0x0?)<br>	/tmp/sandbox143763375/prog.go:14 +0x71<br>created by main.main<br>	/tmp/sandbox143763375/prog.go:23 +0x98<br><br><strong>goroutine 19 [chan receive]:</strong><br>main.ReceiveAndSend(0x0?, 0x0?)<br>	/tmp/sandbox143763375/prog.go:14 +0x71<br>created by main.main<br>	/tmp/sandbox143763375/prog.go:24 +0x105</pre><p>Both the goroutine 18 and 19 waits to recieve the data from the channel.</p><h3>Summary</h3><p>Hope this article introduces you some of the new concepts in Goroutines.</p><p>Happy Learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a875fc0cc9a1" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/more-on-go-routines-a875fc0cc9a1">More on Go routines</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>