<?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 UnicornOnAzur on Medium]]></title>
        <description><![CDATA[Stories by UnicornOnAzur on Medium]]></description>
        <link>https://medium.com/@unicornonazur?source=rss-6f9dea21fd41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*451U1dMoNvSTXAl-CVLJgw.png</url>
            <title>Stories by UnicornOnAzur on Medium</title>
            <link>https://medium.com/@unicornonazur?source=rss-6f9dea21fd41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:34:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@unicornonazur/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[The brilliance of the smtplib library: unwrapping the code to see what it does.]]></title>
            <link>https://medium.com/top-python-libraries/the-brilliance-of-the-smtplib-library-unwrapping-the-code-to-see-what-it-does-de3c66be07ee?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3c66be07ee</guid>
            <category><![CDATA[python-standard-library]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[smtplib]]></category>
            <category><![CDATA[email]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 03:38:33 GMT</pubDate>
            <atom:updated>2026-08-31T03:38:33.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s explore the smtplib library to see what is handled us, the end user.</p><p>After writing a story on how to send an email using the smtplib and email libraries, I saw that there were multiple functions in the smtplib library among which the sendmail and send_message are the most high level ones. I had skimmed through how the Simple Mail Transfer Protocol (SMTP) operates, and seeing those terms pop up in the function names got me curious about peeling back the layers to reveal the “conversation” between the two parties. I also wanted to find out which libraries support smtplib. Turns out, it’s <em>sockets all the way down!</em></p><blockquote><strong>Disclaimer: </strong>the code examples below work, but they’re designed for very specific scenarios, and all checks and error handling have been stripped away. So, please don’t use this code without being aware of the potential issues!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxvivaJYivNzWDWPzWjvrQ.jpeg" /><figcaption>Image generated with magicstudio.com</figcaption></figure><p>To send an email we’ll need to do the following actions¹’²:</p><p><strong>Create the email</strong></p><ul><li>Create the body and the header;</li></ul><p><strong>Handshake</strong></p><ul><li>Establish a connection with the server;</li><li>Learn a server’s supported options by <strong>&quot;HELO&quot; or &quot;EHLO&quot;;</strong></li><li>Secure connection <strong>&quot;STARTTLS&quot;;</strong></li><li>Learn a server’s supported options by <strong>&quot;HELO&quot; or &quot;EHLO&quot;;</strong></li><li>Authenticate <strong>&quot;AUTH&quot;;</strong></li><li>Provide sender <strong>&quot;MAIL FROM&quot;;</strong></li><li>Provide recipients <strong>&quot;RCPT TO&quot;;</strong></li></ul><p><strong>Email transfer</strong></p><ul><li>Send the data <strong>&quot;DATA&quot;;</strong></li></ul><p><strong>Termination</strong></p><ul><li>Close the connection <strong>&quot;QUIT&quot;</strong>.</li></ul><h3>Unwrapping how to send an email with smtplib</h3><p>I’ll start with the most high level approach to sending an email like I did in my previous story and work down.</p><h4>0. Setup</h4><p>Before we create or send any email, we’ll setup the script with imports and variables.</p><pre># Imports needed directly<br>import os<br>import smtplib<br>import dotenv<br># Imports needed eventually<br>from email.base64mime import body_encode as encode_base64<br>import re<br>import socket<br>import ssl<br># Load variables<br>dotenv.load_dotenv()<br>username = os.getenv(&quot;GOOGLE_USERNAME&quot;, &quot;&quot;)<br>password = os.getenv(&quot;GOOGLE_APP_PASSWORD&quot;, &quot;&quot;)<br>host= &quot;smtp.gmail.com&quot;<br>port = 587<br>title = &quot;title&quot;<br>body = &quot;body&quot;<br>MAXLINE = 8192</pre><h4>1. The high level approach</h4><p><a href="https://medium.com/pythoneers/its-just-as-easy-as-sending-an-email-61a854981262">It’s just as easy as sending an email.</a></p><p>Taking the code I came to in the previous story, we’ll start with this script to create and send an email using (G)SMTP, Google SMTP, and TLS, Transport Layer Security. We create an email message using the email library, and then using the SMTP object as a context manager we connect, start TLS, login, send the mail, and close.</p><pre>import email.message<br><br>message = email.message.EmailMessage()<br>message[&quot;Subject&quot;] = f&quot;{title} 1&quot;<br>message[&quot;From&quot;] = user<br>message[&quot;To&quot;] = user<br>message.set_content(body)<br><br># Connect<br>with smtplib.SMTP(host=host, port=port) as smtp_server:<br>    # Start TLS<br>    smtp_server.starttls()<br>    # Login<br>    smtp_server.login(user=user, password=password)<br>    # Send mail<br>    smtp_server.send_message(message)<br># Close</pre><p>To keep track of the major steps in the code I added comments in between the lines for connect, start TLS, login, send mail and close. I have structured the “unwrapping” of the methods so that we come to the same underlying methods for all in the same step.</p><h4>2. Remove the context manager, unpack the login method and replace the send_message method.</h4><p>The first things we can change are the context manager, the email object, and two methods:</p><ul><li>Replace the send_message method with the sendmail method since the only difference is that the message is no longer a Message object³.</li><li>Replace the EmailMessage object with a constructed bytes string.</li><li>Not using the context manager:<br>- Therefore we need to call the connect and quit functions.</li><li>Unpack the login function which in essence consists of:<br>- Call the ehlo_or_helo_if_needed method;<br>- Prepare the variables;<br>- Call the auth method.</li></ul><pre>message = &quot;\r\n&quot;.join([f&quot;Subject: {title} 2&quot;,<br>                        f&quot;From: {user}&quot;, f&quot;To: {user}&quot;,<br>                        &#39;Content-Type: text/plain; charset=&quot;utf-8&quot;&#39;,<br>                        &quot;Content-Transfer-Encoding: 7bit&quot;,<br>                        &quot;MIME-Version: 1.0\r\n&quot;,<br>                        body, &quot;&quot;]).encode(&quot;utf-8&quot;)<br>smtp_server = smtplib.SMTP()<br># Connect<br>smtp_server.connect(host=host, port=port)<br># Start TLS<br>smtp_server.starttls()<br># Login<br>smtp_server.ehlo_or_helo_if_needed()<br>authmethod = &quot;plain&quot;<br>smtp_server.user, smtp_server.password = user, password<br>method_name = &quot;auth_&quot; + authmethod.lower().replace(&quot;-&quot;, &quot;_&quot;)<br>smtp_server.auth(authmethod, getattr(smtp_server, method_name), initial_response_ok=True)<br># Send mail<br>smtp_server.sendmail(user, user, message)<br># Close<br>smtp_server.quit()</pre><h4>3. Expose all the docmd methods</h4><p>In this step we want to expose all the docmd methods since that is in almost every higher level method. Therefore, we need to do the following:</p><ul><li>Unpack the starttls method;<br>- Call the ehlo_or_helo_if_needed method;<br>- Use docmd to send STARTTLS;<br>- Create an unverified SSL context for the socket.</li><li>Unpack the auth method;<br>- Use gettattr to retrieve the required method by name;<br>- Use the method to retrieve an initial response;<br>- Encode the response and use docmd to send it.</li><li>Unpack the sendmail method;<br>- Call the ehlo_or_helo_if_needed method;<br>- Call the mail method to add a sender;<br>- Call the rcpt method to add recipients;<br>- Call the data method to send the message;</li><li>Unpack the quit method;<br>- Use docmd to send quit;<br>- Call the close method to close the file and socket.</li></ul><pre>from email.base64mime import body_encode as encode_base64<br>import ssl<br><br>message = &quot;\r\n&quot;.join([f&quot;Subject: {title} 3&quot;,<br>                        f&quot;From: {user}&quot;, f&quot;To: {user}&quot;,<br>                        &#39;Content-Type: text/plain; charset=&quot;utf-8&quot;&#39;,<br>                        &quot;Content-Transfer-Encoding: 7bit&quot;,<br>                        &quot;MIME-Version: 1.0\r\n&quot;,<br>                        body, &quot;&quot;]).encode(&quot;utf-8&quot;)<br>smtp_server = smtplib.SMTP()<br># Connect<br>smtp_server.connect(host=host, port=port)<br># Start TLS<br>smtp_server.ehlo_or_helo_if_needed()<br>(resp, _) = smtp_server.docmd(&quot;STARTTLS&quot;)<br>if resp == 220:<br>    context = ssl._create_stdlib_context()<br>smtp_server.sock = context.wrap_socket(smtp_server.sock,<br>                                        server_hostname=smtp_server._host)<br>smtp_server.file = None<br>smtp_server.ehlo_resp = None<br># Login<br>smtp_server.ehlo_or_helo_if_needed()<br>authmethod = &quot;PLAIN&quot;<br>smtp_server.user, smtp_server.password = user, password<br>method_name = &quot;auth_&quot; + authmethod.lower().replace(&quot;-&quot;, &quot;_&quot;)<br>authobject = getattr(smtp_server, method_name)<br>initial_response = authobject()<br>response = encode_base64(initial_response.encode(smtp_server.command_encoding), eol=&#39;&#39;)<br>_ = smtp_server.docmd(&quot;AUTH&quot;, authmethod + &quot; &quot; + response)<br># Send mail<br>smtp_server.ehlo_or_helo_if_needed()<br>smtp_server.mail(user)<br>smtp_server.rcpt(user)<br>smtp_server.data(message)<br># Close<br>smtp_server.docmd(&quot;quit&quot;)<br>smtp_server.close()</pre><h4>4. Replace nearly everything with putcmd and getreply.</h4><p>Since nearly every method uses a putcmd and getreply method, we’ll now replace every method that does that.</p><pre>def docmd(self, cmd, args=&quot;&quot;):<br>    &quot;&quot;&quot;Send a command, and return its response code.&quot;&quot;&quot;<br>    self.putcmd(cmd, args)<br>    return self.getreply()</pre><ul><li>Replace every docmd method with a putcmd and getreply method, and only take the return value when needed;</li><li>Replace every ehlo_or_helo_if_needed method with a putcmd and getreply method, and only store the ehlo message when needed;</li><li>Replace mail and rcpt methods with a putcmd and getreply method;<br>- One small part is replacing the function inside themail and rcpt methods that is used to parse the email address.</li><li>Replace data method with a putcmd and getreply method, and use a send method to send the prepared message in bytes.</li></ul><pre>import email.utils<br><br>message = &quot;\r\n&quot;.join([f&quot;Subject: {title} 4&quot;,<br>                        f&quot;From: {user}&quot;, f&quot;To: {user}&quot;,<br>                        &#39;Content-Type: text/plain; charset=&quot;utf-8&quot;&#39;,<br>                        &quot;Content-Transfer-Encoding: 7bit&quot;,<br>                        &quot;MIME-Version: 1.0\r\n&quot;,<br>                        body, &quot;&quot;]).encode(&quot;utf-8&quot;)<br>smtp_server = smtplib.SMTP()<br># Connect<br>smtp_server.connect(host=host, port=port)<br># Start TLS<br>smtp_server.putcmd(smtp_server.ehlo_msg, smtp_server.local_hostname)<br>(_, msg) = smtp_server.getreply()<br>smtp_server.ehlo_resp = msg<br>smtp_server.putcmd(&quot;STARTTLS&quot;)<br>(resp, _) = smtp_server.getreply()<br>if resp == 220:<br>    context = ssl._create_stdlib_context()<br>smtp_server.sock = context.wrap_socket(smtp_server.sock,<br>                                        server_hostname=smtp_server._host)<br>smtp_server.file = None<br>smtp_server.ehlo_resp = None<br># Login<br>smtp_server.putcmd(smtp_server.ehlo_msg, smtp_server.local_hostname)<br>smtp_server.getreply()<br>authmethod = &quot;plain&quot;<br>smtp_server.user, smtp_server.password = user, password<br>method_name = &quot;auth_&quot; + authmethod.lower().replace(&quot;-&quot;, &quot;_&quot;)<br>authobject = getattr(smtp_server, method_name)<br>initial_response = authobject()<br>response = encode_base64(initial_response.encode(smtp_server.command_encoding), eol=&#39;&#39;)<br>smtp_server.putcmd(&quot;AUTH&quot;, authmethod + &quot; &quot; + response)<br>smtp_server.getreply()<br># Send mail<br>smtp_server.putcmd(smtp_server.ehlo_msg, smtp_server.local_hostname)<br>smtp_server.getreply()<br>_, addr = email.utils.parseaddr(user)<br>smtp_server.putcmd(&quot;mail&quot;, f&quot;from:&lt;{addr}&gt;&quot;)<br>smtp_server.getreply()<br>smtp_server.putcmd(&quot;rcpt&quot;, f&quot;to:&lt;{addr}&gt;&quot;)<br>smtp_server.getreply()<br>smtp_server.putcmd(&quot;data&quot;)<br>smtp_server.getreply()<br>message_bytes = re.sub(br&quot;(?m)^\.&quot;, b&quot;..&quot;, message)<br>if message_bytes[-2:] != smtplib.bCRLF:<br>    message_bytes = message_bytes + smtplib.bCRLF<br>message_bytes = message_bytes + b&quot;.&quot; + smtplib.bCRLF<br>smtp_server.send(message_bytes)<br>smtp_server.getreply()<br># Close<br>smtp_server.putcmd(&quot;quit&quot;)<br>smtp_server.close()</pre><h4>5. Replace every putcmd</h4><p>The putcmd method is basically a wrapper for the send method when you look at the source code.</p><pre>def putcmd(self, cmd, args=&quot;&quot;):<br>    &quot;&quot;&quot;Send a command to the server.&quot;&quot;&quot;<br>    ...<br>    self.send(f&#39;{s}{CRLF}&#39;)</pre><ul><li>Replace every putcmd method with a send method and to allow that replace every string with its bytes version;</li><li>Substitute email.utils.parseaddr(user) with simply put the variable user in the string (which just happens to be exactly the same in this example);</li></ul><pre>message = &quot;\r\n&quot;.join([f&quot;Subject: {title} 5&quot;,<br>                        f&quot;From: {user}&quot;, f&quot;To: {user}&quot;,<br>                        &#39;Content-Type: text/plain; charset=&quot;utf-8&quot;&#39;,<br>                        &quot;Content-Transfer-Encoding: 7bit&quot;,<br>                        &quot;MIME-Version: 1.0\r\n&quot;,<br>                        body, &quot;&quot;]).encode(&quot;utf-8&quot;)<br>smtp_server = smtplib.SMTP()<br># Connect<br>smtp_server.connect(host=host, port=port)<br># Start TLS<br>smtp_server.send(f&quot;{smtp_server.ehlo_msg} {smtp_server.local_hostname} {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>(_, msg) = smtp_server.getreply()<br>smtp_server.ehlo_resp = msg<br>smtp_server.send(f&quot;STARTTLS {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>(resp, _) = smtp_server.getreply()<br>if resp == 220:<br>    context = ssl._create_stdlib_context()<br>smtp_server.sock = context.wrap_socket(smtp_server.sock,<br>                                        server_hostname=smtp_server._host)<br>smtp_server.file = None<br>smtp_server.ehlo_resp = None<br># Login<br>smtp_server.send(f&quot;{smtp_server.ehlo_msg} {smtp_server.local_hostname} {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.getreply()<br>authmethod = &quot;plain&quot;<br>smtp_server.user, smtp_server.password = user, password<br>method_name = &quot;auth_&quot; + authmethod.lower().replace(&quot;-&quot;, &quot;_&quot;)<br>authobject = getattr(smtp_server, method_name)<br>initial_response = authobject()<br>response = encode_base64(initial_response.encode(smtp_server.command_encoding), eol=&#39;&#39;)<br>smtp_server.send(f&quot;AUTH {authmethod} {response}{smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.getreply()<br># Send mail<br>smtp_server.send(f&quot;{smtp_server.ehlo_msg} {smtp_server.local_hostname} {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.getreply()<br>smtp_server.send(f&quot;mail from:&lt;{user}&gt; {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.getreply()<br>smtp_server.send(f&quot;rcpt to:&lt;{user}&gt; {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.getreply()<br>smtp_server.send(f&quot;data {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.getreply()<br>message_bytes = re.sub(br&quot;(?m)^\.&quot;, b&quot;..&quot;, message)<br>if message_bytes[-2:] != smtplib.bCRLF:<br>    message_bytes = message_bytes + smtplib.bCRLF<br>message_bytes = message_bytes + b&quot;.&quot; + smtplib.bCRLF<br>smtp_server.sock.sendall(message_bytes)<br>smtp_server.getreply()<br># Close<br>smtp_server.send(f&quot;quit {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.close()</pre><h4>6. Get to the socket handling</h4><p>At this point we’ve come from the original four to just over 40 lines, to do the same simple task. We’ll now strip away all things to get to the direct handling of the socket. There are two methods that handle the socket, our end of the connection with the server, namely send and getreply. As we can see in the source code, the essence of the method is calling a method on the socket.</p><pre>def send(self, s):<br>    &quot;&quot;&quot;Send &#39;s&#39; to the server.&quot;&quot;&quot;<br>    self.sock.sendall(s)</pre><p>The same with the other method.</p><pre>def getreply(self):<br>    if self.file is None:<br>        self.file = self.sock.makefile(&#39;rb&#39;)</pre><ul><li>Replace the connect method with the _get_socket method;</li><li>Replace every send method with sock.sendall;</li><li>Replace every getreply method with sock.makefile;</li><li>Remove the unneeded file variable.</li></ul><pre>message = &quot;\r\n&quot;.join([f&quot;Subject: {title} 6&quot;,<br>                        f&quot;From: {user}&quot;, f&quot;To: {user}&quot;,<br>                        &#39;Content-Type: text/plain; charset=&quot;utf-8&quot;&#39;,<br>                        &quot;Content-Transfer-Encoding: 7bit&quot;,<br>                        &quot;MIME-Version: 1.0\r\n&quot;,<br>                        body, &quot;&quot;]).encode(&quot;utf-8&quot;)<br>smtp_server = smtplib.SMTP()<br># Connect<br>smtp_server.sock = smtp_server._get_socket(host, port, smtp_server.timeout)<br>smtp_server._host = host<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br># Start TLS<br>smtp_server.sock.sendall(f&quot;{smtp_server.ehlo_msg} {smtp_server.local_hostname} {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>msg = smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)[4:]<br>smtp_server.ehlo_resp = msg<br>smtp_server.sock.sendall(f&quot;STARTTLS {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>lines = smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br>resp = int(lines[:3])<br>if resp == 220:<br>    context = ssl._create_stdlib_context()<br>smtp_server.sock = context.wrap_socket(smtp_server.sock,<br>                                        server_hostname=smtp_server._host)<br>smtp_server.ehlo_resp = None<br># Login<br>smtp_server.sock.sendall(f&quot;{smtp_server.ehlo_msg} {smtp_server.local_hostname} {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br>authmethod = &quot;plain&quot;<br>smtp_server.user, smtp_server.password = user, password<br>method_name = &quot;auth_&quot; + authmethod.lower().replace(&quot;-&quot;, &quot;_&quot;)<br>authobject = getattr(smtp_server, method_name)<br>initial_response = authobject()<br>response = encode_base64(initial_response.encode(smtp_server.command_encoding), eol=&#39;&#39;)<br>smtp_server.sock.sendall(f&quot;AUTH {authmethod} {response}{smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br># Send mail<br>smtp_server.sock.sendall(f&quot;{smtp_server.ehlo_msg} {smtp_server.local_hostname} {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br>smtp_server.sock.sendall(f&quot;mail from:&lt;{user}&gt; {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br>smtp_server.sock.sendall(f&quot;rcpt to:&lt;{user}&gt; {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br>smtp_server.sock.sendall(f&quot;data {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br>message_bytes = re.sub(br&quot;(?m)^\.&quot;, b&quot;..&quot;, message)<br>if message_bytes[-2:] != smtplib.bCRLF:<br>    message_bytes = message_bytes + smtplib.bCRLF<br>message_bytes = message_bytes + b&quot;.&quot; + smtplib.bCRLF<br>smtp_server.sock.sendall(message_bytes)<br>smtp_server.sock.makefile(&quot;rb&quot;).readline(MAXLINE)<br># Close<br>smtp_server.sock.sendall(f&quot;quit {smtplib.CRLF}&quot;.encode(&quot;utf-8&quot;))<br>smtp_server.sock.close()</pre><h4>7. Remove everything from smtplib</h4><p>Finally, we’ll remove every last thing from the smtplib library to see what we are dealing with. To do that, we need the socket library and we need to create some of the variables ourselves.</p><ul><li>Get the local hostname by calling socket.getfqdn;<br>- getfqdn returns a fully qualified domain name for <em>name</em> or localhost<em>.⁵</em></li><li>Replace _get_socket by socket.create_connection;<br>- Connect to a TCP service listening on the internet <em>address</em> (a 2-tuple (host, port)), and return the socket object.⁵</li><li>Replace all references to smtp_server.sock with socket_;</li><li>Replace the specific auth method we used with a lambda function;</li><li>Create all the needed variables ourselves.</li></ul><pre>message = &quot;\r\n&quot;.join([f&quot;Subject: {title} 7&quot;,<br>                        f&quot;From: {user}&quot;,<br>                        f&quot;To: {user}&quot;,<br>                        &#39;Content-Type: text/plain; charset=&quot;utf-8&quot;&#39;,<br>                        &quot;Content-Transfer-Encoding: 7bit&quot;,<br>                        &quot;MIME-Version: 1.0\r\n&quot;,<br>                        body, &quot;&quot;]).encode(&quot;utf-8&quot;)<br>ehlo_msg = &quot;ehlo&quot;<br>local_hostname = socket.getfqdn()<br># Connect<br>socket_ = socket.create_connection((host, port))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br># Start TLS<br>socket_.sendall(f&quot;{ehlo_msg} {local_hostname} {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>socket_.sendall(f&quot;STARTTLS {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>lines = socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>resp = int(lines[:3])<br>if resp == 220:<br>    context = ssl._create_stdlib_context()<br>socket_ = context.wrap_socket(socket_, server_hostname=host)<br># Login<br>socket_.sendall(f&quot;{ehlo_msg} {local_hostname} {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>authmethod = &quot;plain&quot;<br>authobject = lambda: &quot;\0%s\0%s&quot; % (user, password)<br>initial_response = authobject()<br>response = encode_base64(initial_response.encode(&#39;ascii&#39;), eol=&#39;&#39;)<br>socket_.sendall(f&quot;AUTH {authmethod} {response}{CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br># Send mail<br>socket_.sendall(f&quot;{ehlo_msg} {local_hostname} {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>socket_.sendall(f&quot;mail from:&lt;{user}&gt; {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>socket_.sendall(f&quot;rcpt to:&lt;{user}&gt; {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>socket_.sendall(f&quot;data {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br>message_bytes = re.sub(br&quot;(?m)^\.&quot;, b&quot;..&quot;, message)<br>if message_bytes[-2:] != bCRLF:<br>    message_bytes = message_bytes + bCRLF<br>message_bytes = message_bytes + b&quot;.&quot; + bCRLF<br>socket_.sendall(message_bytes)<br>socket_.makefile(&quot;rb&quot;).readline(MAXLINE)<br># Close<br>socket_.sendall(f&quot;quit {CRLF}&quot;.encode(&quot;utf-8&quot;))<br>socket_.close()</pre><p>So now we can see that in the end smtplib library is a beautiful cover over socket handling with the socket library. Yes, you could unpack the socket library, and the other libraries, but this is where I’ll round up.</p><h3>See the conversation in the connection</h3><p>By printing both the strings/bytes we send and receive, we get some inside in the conversation that takes place between our computer and the server. In the output below I’ve highlighted the key words. It’s nice to see the politeness of this conversation.</p><pre>Sent:           <strong>ehlo </strong>__laptop__.home<br>Received:       250 b&#39;smtp.gmail.com at your service, [87.208.168.239]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nSMTPUTF8&#39;<br>Sent:           <strong>STARTTLS</strong><br>Received:       220 b&#39;2.0.0 Ready to start TLS&#39;<br>Sent:           <strong>ehlo </strong>__laptop__.home<br>Received:       250 b&#39;smtp.gmail.com at your service, [87.208.168.239]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nSMTPUTF8&#39;<br>Sent:           <strong>AUTH</strong><br>Received:       235 b&#39;2.7.0 Accepted&#39;<br>Sent:           ehlo __laptop__.home<br>Received:       250 b&#39;smtp.gmail.com at your service, [87.208.168.239]\nSIZE 35882577\n8BITMIME\nAUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\nENHANCEDSTATUSCODES\nPIPELINING\nSMTPUTF8&#39;<br>Sent:           <strong>mail from</strong>:...<br>Received:       250 b&#39;2.1.0 OK a640c23a62f3a-c2553ee6b3csm32373466b.61 - gsmtp&#39;<br>Sent:           <strong>rcpt to</strong>:...<br>Received:       250 b&#39;2.1.5 OK a640c23a62f3a-c2553ee6b3csm32373466b.61 - gsmtp&#39;<br>Sent:           <strong>data</strong><br>Received:       354 b&#39;Go ahead a640c23a62f3a-c2553ee6b3csm32373466b.61 - gsmtp&#39;<br>Sent:           b&#39;Subject: title verbose\r\nFrom: ...\r\nTo: ...\r\nContent-Type: text/plain; charset=&quot;utf-8&quot;\r\nContent-Transfer-Encoding: 7bit\r\nMIME-Version: 1.0\r\n\r\nbody\r\n.\r\n&#39;<br>Received:       250 b&#39;2.0.0 OK  1787861249 a640c23a62f3a-c2553ee6b3csm32373466b.61 - gsmtp&#39;<br>Sent:           <strong>quit</strong><br>Received:       221 b&#39;2.0.0 closing connection a640c23a62f3a-c2553ee6b3csm32373466b.61 - gsmtp&#39;</pre><h3>To conclude</h3><p>Getting all the seven steps/variations of sending an email to work was a process of trying and failing. Especially, finding out that I needed to read/clear the socket before sending something else was sent. After a while have sorted the unwrapping steps of all the different methods in similar steps, I was better at understanding how the library works. I will probably still not have understand all of it. What I found most interesting is the large amount of error handling, and specific protocol preparation that is done for the user. All in all, it was a nice experience.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: <a href="https://github.com/UnicornOnAzur/">https://github.com/UnicornOnAzur/.</a></blockquote><p>[1] <a href="https://mailtrap.io/blog/smtp-commands-and-responses/">https://mailtrap.io/blog/smtp-commands-and-responses/</a></p><p>[2] <a href="https://www.afternerd.com/blog/smtp/">https://www.afternerd.com/blog/smtp/</a></p><p>[3] <a href="https://docs.python.org/3/library/smtplib.html">https://docs.python.org/3/library/smtplib.html</a></p><p>[4] <a href="https://web.mit.edu/6.005/www/fa16/classes/21-sockets-networking/">https://web.mit.edu/6.005/www/fa16/classes/21-sockets-networking/</a></p><p>[5] <a href="https://docs.python.org/3/library/socket.html">https://docs.python.org/3/library/socket.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3c66be07ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/the-brilliance-of-the-smtplib-library-unwrapping-the-code-to-see-what-it-does-de3c66be07ee">The brilliance of the smtplib library: unwrapping the code to see what it does.</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How many reps is it today? What is my 1RM? Solving common Crossfit issues with math and Python.]]></title>
            <link>https://medium.com/codetodeploy/how-many-reps-is-it-today-what-is-my-1rm-solving-common-crossfit-issues-with-math-and-python-3e92564d2753?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e92564d2753</guid>
            <category><![CDATA[arithmetic-progression]]></category>
            <category><![CDATA[crossfit]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 04:16:40 GMT</pubDate>
            <atom:updated>2026-08-16T04:16:40.871Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Get the total of reps from a progression and calculate your 1RM both without a calculator and with Python functions.</em></p><p>Every once in a while, I’ll be waiting for the Crossfit class to start and wonder, together with the other athletes, how many reps they’ll make us do. Or, when doing a strengt training, what your 1RM, 3RM or 5RM is. How do you get those answers quickly without resorting to your phone or looking it up in tables.</p><figure><img alt="Weight training time" src="https://cdn-images-1.medium.com/max/1024/0*iryHk6QMXKxN3d5I" /><figcaption>Photo by <a href="https://unsplash.com/@samuelgirven?utm_source=medium&amp;utm_medium=referral">Samuel Girven</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>total = ((smallest set + largest set) * number of series)/2</pre><blockquote><em>💥 </em><strong><em>Master AI &amp; Tech Skills </em></strong><br> 💥 Crack Every Tech Interview with Confidence<br> 🔥 Up to <strong>70% OFF</strong> — Limited-Time Offer<br> <a href="https://www.educative.io/unlimited?aff=xkRD"><em>👉 </em><strong><em>Enroll Now &amp; Start Learning</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITogvtC6mF2BUF35Qsd9pg.png" /></figure><p>The short answer is that the formula above gets you the rep total for a progression of reps, such as 12–9–6, and getting your 1RM from your 3RM or 5RM can be estimated by adding 10% and rounding up to the nearest multiple of 5. If your 5RM was 80kg, adding 10% makes 88kg and round it up to the next multiple of 5 gets you 90kg. Let’s break down why these work… and combine with my other hobby Python by also making it into functions.</p><h3>What is the rep total?</h3><h4>By hand</h4><p>Most workouts have sets/rounds with the same amount of reps or a progression of reps, usually decreasing in size. In the first case, it’s back to the multiplication tables. <strong>Boring, I know! </strong>But it is the quickest way.</p><p>For the others there is a beautifully simple formula. Take the reps for the WOD FRAN for instance. This has two decreasing series of reps: one for the thrusters and one for the pull-ups. With this amount simply summing the total is a perfect alternative but it helps us understand the approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*l6M8qU_Fr3hq1opAiyORSQ.jpeg" /></figure><p>To sum a(<em>n arithmetic</em>) progression, which does require that the difference between the reps aka the step is the same for the entire sequence, you take the smallest and the largest number and add them together. Then you multiple it by the number of series. Lastly, you take half of that and that’s the total.</p><pre>total = ((smallest set + largest set) * number of series)/2</pre><p>Let’s take the thrusters as an example. The smallest amount is <strong>9</strong> and the largest is <strong>21</strong>. That is <strong>30</strong> together. 30 times 3 series is <strong>90</strong>. And half of that is <strong>45</strong>.</p><h4>Python</h4><p>sum_progression(series): This function calculates the sum of the series, returning a specific formula for arithmetic progressions or the sum of the series if it is not an arithmetic progression.</p><pre>import itertools<br><br>def is_progression(series) -&gt; bool:<br>    return 1 == len({b - a for a, b in itertools.pairwise(sorted(series))})<br><br>def sum_progression(series) -&gt; int:<br>    if is_progression(series):<br>        return (len(series) * (min(series) + max(series)))//2<br>    return sum(series)<br><br></pre><p>is_progression(series): This function checks if the provided series is an arithmetic progression. A set comprehension computes the differences between each pair where the pairwise function generates pairs of consecutive elements from the sorted series.</p><h3>What is my 1RM?</h3><h4>by hand</h4><p><strong>3RM</strong> is estimated to be around 93% of your 1RM. So multiplying your 3RM by 1.08 gets you your 1RM.</p><p><strong>5RM</strong></p><p>To calculate the 1RM from your 5RM there are two formulas. Brzycki’s formula which comes to 112.5% of your 5RM:</p><pre>1RM = 5RM * (36/32)</pre><p>Epley’s formula which comes to 116% of your 5RM:</p><pre>1RM = 5RM * (35/30)</pre><p>Since these formulas are just estimations, we can come up with a simple workflow. So if you know your 5RM there are three options:</p><ol><li>If you can divide it by 6, add one sixth to the weight;</li><li>If you can divide it by 8, add one eigth to the weight;</li><li>Otherwise add one tenth to the weight and round it up to the next multiple of 5.</li></ol><p>Will it work: for 200 lbs Brzycki’s comes to 225 and option 3 gets 200 plus 20 is 220 rounded to the next multiple is 225. For 80 kgs Brzycki’s comes to 90 and option 3 gets 80 plus 8 makes 88 which is rounded to 90.</p><p>Yes, it works. It does get closer to Brzycki’s than Epley’s most of the time, so know that it is your lower end of the estimated 1RM.</p><blockquote>If you want to use a phone or computer to get your 1RM, you could use: <a href="https://calculator.academy/">https://calculator.academy/</a>.</blockquote><h4>Python</h4><p>Apart from some trick to get the next multiple this is very easily implemented in Python:</p><pre><br>from math import ceil<br>def what_is_my_1rm(weight: int, rm: int = 3):<br>    _3RM, _5RM = 3, 5<br><br>    calculated_weight = weight * 1.1<br><br>    if rm == _3RM:<br>        return round(calculated_weight)<br>    elif rm == _5RM:<br>        return ceil(calculated_weight + (-calculated_weight % 5))<br>    else:<br>        raise ValueError(&quot;Invalid value for rm. Only 3 or 5 are accepted.&quot;)<br></pre><p>It multiplies the weight by a factor (1.1) to estimate the 1RM. Depending on whether the user specifies a 3RM or 5RM, it rounds the calculated weight accordingly. If rm is 5, it rounds up to the nearest multiple of 5 using the ceil function. This is done by adding the negative modulus of the calculated weight with respect to 5, ensuring that the result is a multiple of 5. If an invalid RM value is provided, it raises a ValueError.</p><h3>To conclude</h3><p>This combination of three things I like, Crossfit, math, and Python, is amazing. I can’t wait for my next class to use it. Let me know if it works for you.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: https://github.com/UnicornOnAzur/.</blockquote><p>[1]</p><p>[] Matthew Brzycki. Strength Testing—Predicting a One-Rep Max from Reps-to-Fatigue, 1993.</p><p>[]</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9QTaaaxboQP_gKSLedW_w.png" /></figure><p>👉 Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></p><p>👉 Follow us: <a href="https://www.linkedin.com/in/bhuwan-kc-583505319/?isSelfProfile=true"><strong>Linkedin</strong></a>| <a href="https://medium.com/codetodeploy"><strong>Medium</strong></a></p><p>👉 CodeToDeploy Tech Community is live on Discord — <a href="https://discord.gg/ZpwhHq6D"><strong>Join now!</strong></a></p><p><strong>Disclosure:</strong> This post includes affiliate and partnership links.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e92564d2753" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetodeploy/how-many-reps-is-it-today-what-is-my-1rm-solving-common-crossfit-issues-with-math-and-python-3e92564d2753">How many reps is it today? What is my 1RM? Solving common Crossfit issues with math and Python.</a> was originally published in <a href="https://medium.com/codetodeploy">CodeToDeploy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can I create a constant in Python? No, but I can get close.]]></title>
            <link>https://medium.com/codetodeploy/can-i-create-a-constant-in-python-no-but-i-can-get-close-263413d8fa5e?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/263413d8fa5e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[constant]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 05:42:02 GMT</pubDate>
            <atom:updated>2026-08-15T05:42:02.295Z</atom:updated>
            <content:encoded><![CDATA[<p>This time in “Can I make it in Python?”, I try to recreate the constant such as exists in other programming languages.</p><figure><img alt="3.141592653589793238462643383279502884197" src="https://cdn-images-1.medium.com/max/1024/0*k4LcrpByoMhkqw5I" /><figcaption>Photo by <a href="https://unsplash.com/@tasokats?utm_source=medium&amp;utm_medium=referral">Taso Katsionis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>💥 </em><strong><em>Master AI &amp; Tech Skills </em></strong><br> 💥 Crack Every Tech Interview with Confidence<br> 🔥 Up to <strong>70% OFF</strong> — Limited-Time Offer<br> <a href="https://www.educative.io/unlimited?aff=xkRD"><em>👉 </em><strong><em>Enroll Now &amp; Start Learning</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITogvtC6mF2BUF35Qsd9pg.png" /></figure><p>Early on in learning Python, I read that the language doesn’t support a constant. With some experience in other programming languages I knew that this was possible and often very useful.</p><h3>What defines a constant?</h3><p>Looking at, for example Bash, C++ and Java, a variable defined as a constant has the following attributes:</p><ol><li>▶️ Variable is initialized at definition;</li><li>▶️ Variable name is in all uppercase;</li><li>▶️ Variable name is added to the namespace;</li><li>▶️ Variable cannot be modified:</li></ol><p>a. ▶️ it cannot be reassigned;</p><p>b. ▶️ it cannot be changed in place.</p><p>Let’s see what we can achieve with Python…</p><blockquote>For inspiration you can look <a href="https://stackoverflow.com/questions/3711657/can-i-prevent-modifying-an-object-in-python">here</a>.</blockquote><h3>Creating a Constant class</h3><p>To get a new object, a constant, I created a class called Constant which does the following:</p><ul><li>It sets the variable name in all uppercase (2);</li><li>It adds the variable name to the namespace ie the global scope (3);</li><li>It creates a singleton (4);</li><li>It prevents inplace assignment (4b).</li></ul><pre>import inspect<br>import typing<br><br>class Constant:<br>    _instance: typing.Optional[&#39;Constant&#39;] = None<br><br>    def __new__(cls: type) -&gt; &#39;Constant&#39;:<br>        if cls._instance is None:<br>            cls._instance = super().__new__(cls)<br>            globals()[ cls.__name__.upper()] = cls._instance<br>        else:<br>            print(&quot;Constant already exists.&quot;)<br>        return cls._instance<br><br>    def __str__(self: typing.Self) -&gt; str:<br>        return f&quot;{self.value:.10}&quot;<br><br>    def __repr__(self: typing.Self) -&gt; str:<br>        return f&quot;{self.symbol} = {self.__str__()}&quot;<br><br>    def _warn_and_return_self(self: typing.Self) -&gt; &#39;Constant&#39;:<br>        print(f&quot; This method &#39;{inspect.stack()[1][3]}&#39; is not allowed with a Constant.&quot;)<br>        return self<br><br>    def __mul__(self: typing.Self, other: float) -&gt; float:<br>        return self.value * other<br><br>    def __rmul__(self: typing.Self, other: float) -&gt; float:<br>        return other * self.value<br><br>    def __imul__(self: typing.Self, _: float) -&gt; typing.Self:<br>        return self._warn_and_return_self()<br></pre><h4>Set the variable name in all capitals</h4><p>To get the variable name you can get the __name__ attribute from the (sub)class instance.¹ Then calling the upper method returns a string in uppercase.</p><pre>cls.__name__.upper()</pre><h4>Add to namespace</h4><p>You can add things to the namespace by using globals() to get the current dictionary of global variables and set it.²</p><pre>globals()[name] = object</pre><h4>Singleton</h4><p>Using GeeksforGeeks³ and Pythonmorsels⁴, I recreated the Singleton pattern. This will ensure that there can only be one instance of a (sub)class. This method doesn’t need to be decorated with @staticmethod because it is special cased.⁵</p><pre>class Single:<br>    instance = None<br><br>    def __new__(cls):<br>        if cls.instance is None:<br>            cls.instance = super().__new__(cls)<br>        return cls.instance</pre><p>I’ve extended the method to also add the object to the global namespace.</p><h4>Preventing inplace assignment</h4><p>To prevent inplace assignment you overwrite all the methods that implement the <em>augmented arithmetic assignments</em>. Those are the result of operators such as += and *=. To test the principle, I’ve implemented one.</p><pre>def __imul__(self):<br>    print(warning)<br>    return self</pre><h4>Defining a constant</h4><p>When I create the constant by making a subclass, I also achieve that:</p><ul><li>It initializes at definition (1).</li></ul><pre>import math<br><br>@lambda _:_()<br>class Euler(Constant):<br>    def __init__(self: typing.Self) -&gt; None:<br>        self.value: float = math.e<br>        self.symbol: str = &quot;e&quot;</pre><h4>Initialize at definition</h4><p>By using my favorite IIFE decorator, or in this case IICE Immediately Invoked Class Expression, I get the class to create an instance when the code is read. Although this does ensure that it can only have one instance is created, it defeats the purpose of the Singleton pattern which now becomes more of a safeguard.</p><p>This constant, Euler, now has a str and repr, it is accessible via EULER, is can be used in calculations (when all the relevant methods are overwritten), it guards against being created again and prevents inplace assignment.</p><h3>To conclude</h3><p>Looking at the Constant class and its use, I’ve managed the following:</p><ol><li>✅️ Variable is initialized at definition;</li><li>✅️ Variable name is in all uppercase;</li><li>✅️ Variable name is added to the namespace;</li><li>▶️ Variable cannot be modified:</li></ol><p>a. ▶️ it cannot be reassigned;</p><p>b. ✅️ it cannot be changed in place.</p><p>To prevent the variable name to be reassigned, I looked at Stackoverflow posts (such as <a href="https://stackoverflow.com/questions/65391084/detect-if-a-python-function-was-activated-with-an-assignment-operator-and-shoul">this</a>) but with just sticking to Python I couldn’t find anything that could check and prevent assignment at runtime. If you have an idea, leave a comment.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: https://github.com/UnicornOnAzur/.</blockquote><p>[1] https://docs.python.org/3/library/stdtypes.html#definition.__name__</p><p>[2] https://stackoverflow.com/questions/11813287/insert-variable-into-global-namespace-from-within-a-function#comment92146187_27642440</p><p>[3] https://www.geeksforgeeks.org/python/singleton-pattern-in-python-a-complete-guide/</p><p>[4] https://www.pythonmorsels.com/making-singletons/</p><p>[5] https://docs.python.org/3/reference/datamodel.html#object.__new__</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9QTaaaxboQP_gKSLedW_w.png" /></figure><p>👉 Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></p><p>👉 Follow us: <a href="https://www.linkedin.com/in/bhuwan-kc-583505319/?isSelfProfile=true"><strong>Linkedin</strong></a>| <a href="https://medium.com/codetodeploy"><strong>Medium</strong></a></p><p>👉 CodeToDeploy Tech Community is live on Discord — <a href="https://discord.gg/ZpwhHq6D"><strong>Join now!</strong></a></p><p><strong>Disclosure:</strong> This post includes affiliate and partnership links.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263413d8fa5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetodeploy/can-i-create-a-constant-in-python-no-but-i-can-get-close-263413d8fa5e">Can I create a constant in Python? No, but I can get close.</a> was originally published in <a href="https://medium.com/codetodeploy">CodeToDeploy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When will we be able to do this in Python: bookmarklets, Excel objects and more?]]></title>
            <link>https://medium.com/top-python-libraries/when-will-we-be-able-to-do-this-in-python-bookmarklets-excel-objects-and-more-6438a6d97f78?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/6438a6d97f78</guid>
            <category><![CDATA[python-in-excel]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 13:05:05 GMT</pubDate>
            <atom:updated>2026-08-07T13:05:05.699Z</atom:updated>
            <content:encoded><![CDATA[<p>A summer day dream about some nice things that may lie in the future…</p><figure><img alt="RBY" src="https://cdn-images-1.medium.com/max/1024/0*MSTEN5h8uxood36_" /><figcaption>Photo by <a href="https://unsplash.com/@hojojenks?utm_source=medium&amp;utm_medium=referral">Hojojenks V</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>During a nice summer day at the lake away from my coding setup it is a great time to think about some ideas that could become true in Python. Reading up on some developments and looking at what I wanted to do with the language in the last years, I came at a few ideas.</p><h3>Bookmarklet</h3><blockquote>Bookmarklets are small software applications in the form of a bookmarked link stored in a web browser.¹</blockquote><p>At the moment you can make a bookmarklet using Javascript. It consists of three elements:</p><ol><li>Calling the Javascript Protocol ²;</li><li>Create an IIFE (Immediately Invoked Function Expression);</li><li>Execute the IIFE.</li></ol><p>In an earlier story I’ve looked into how to create an IIFE in Python. So the last two steps are already possible.</p><p><a href="https://medium.com/pythoneers/using-an-iife-and-query-parameters-with-streamlit-taking-a-popular-thing-from-javascript-and-look-f82f50a40070">Using an IIFE and query parameters with Streamlit: taking a popular thing from Javascript and look…</a></p><p>With projects such as Pyscript a lot of functionality is already created for Python.</p><p><a href="https://medium.com/top-python-libraries/pyscript-an-open-source-platform-to-run-python-scripts-in-your-browser-7dc0a31a110c">PyScript: An Open-Source Platform to Run Python Scripts in Your Browser</a></p><p>Sample code for a bookmarklet could be:</p><pre>@lambda _:_()<br>def func():<br>    import webbrowser<br>    webbrowser.open(“https://bbc.com”)</pre><p>At the moment the shorthand `python:` is not (yet) supported and because of the required newlines you need linebreaks, but one can dream of the possibilities this will unlock…</p><h3>Accessing objects in Excel</h3><p>With the introduction of Python in Excel³ a great number of options became available. However, at this moment you do not have the same freedom you get VBA. For good reasons there are restrictions on the input and output of your Python code⁴. But think about the possibilities:</p><ul><li>Using the Chart wizard on your graph;</li><li>Saving the output of your graph or calculations;</li><li>Executing code in Excel at the click of a button;</li><li>…</li></ul><p>Just like the other idea the basis is already there. With some growing support for having more access than just the xl() function, it may become a reality.</p><h3>Closing off</h3><p>So much for daydreaming. Before I close off, are there any Python related dreams you want to share?</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: https://github.com/UnicornOnAzur/.</blockquote><p>[1] https://www.bookmarkllama.com/blog/bookmarklets</p><p>[2] https://learn.microsoft.com/en-us/previous-versions/aa767736(v=vs.85)</p><p>[3] https://support.microsoft.com/en-US/Excel/python/introduction-to-python-in-excel</p><p>[4]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6438a6d97f78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/when-will-we-be-able-to-do-this-in-python-bookmarklets-excel-objects-and-more-6438a6d97f78">When will we be able to do this in Python: bookmarklets, Excel objects and more?</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t forget to deflate your files while zipping them: a tip for using Python’s ZipFile.]]></title>
            <link>https://medium.com/top-python-libraries/dont-forget-to-deflate-your-files-while-zipping-them-a-tip-for-using-python-s-zipfile-40c9a8dd0a95?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c9a8dd0a95</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[zip-file]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 13:04:53 GMT</pubDate>
            <atom:updated>2026-08-07T13:04:53.292Z</atom:updated>
            <content:encoded><![CDATA[<p>Don’t get fooled by the default option when writing to a ZipFile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cPiqPJUCmvv4Pf4GwQ_Ig.jpeg" /><figcaption>Image created with magicstudio.com</figcaption></figure><p>Some time ago I needed to send a colleague hundreds of files that were the output of a selection script. Since I didn’t want to manually select, download and them to an email, I looked online how to create a Zip archive with Python. Taking that inspiration I got a loop going that wrote all the files to an archive. As it took quite some time, I left for meeting. Only to come back to a missed call that I had used an enormous amount of the platform resources. One key lesson I learned is that the default option in Python’s zipfile library do not compress the files and actually use a lot of memory.</p><p>Let’s look at a common proposed usage, this is from the zipfile documentation¹. It works but the file you wrote to it is not compressed.</p><pre>with ZipFile(&#39;spam.zip&#39;, &#39;w&#39;) as myzip:<br>    myzip.write(&#39;eggs.txt&#39;)</pre><p>The key is in using the compression and, if necessary, the compression_level parameters. To understand why we need to look to the ZipFile object in the documentation.</p><h3>Compressing a ZipFile</h3><p>To determine if, how and to what degree the files should be compressed the ZipFile object takes two parameters: compression and compression_level.</p><h4>compression</h4><p>This determines the ZIP compression method to use when writing the archive and should be one of:</p><ul><li>ZIP_STORED: The numeric constant for an uncompressed archive member. This is the default value.</li><li>ZIP_DEFLATED: The numeric constant for the usual ZIP compression method. This requires the zlib module.</li><li>ZIP_BZIP2: The numeric constant for the BZIP2 compression method. This requires the bz2 module.</li><li>ZIP_LZMA: The numeric constant for the LZMA compression method. This requires the lzma module.</li><li>ZIP_ZSTANDARD: The numeric constant for Zstandard compression. This requires the compression.zstd module.</li></ul><p>Handling compressed archives requires optional modules such as zlib, bz2, lzma, and compression.zstd. When an optional module is not found it will raise an error.¹</p><h4>compresslevel</h4><p>The level sets the tradeoff between speed and compression. Every module has a default level. Most of it is explained well in the documentation.</p><ul><li>ZIP_STORED: This has no effect.¹</li><li>ZIP_DEFLATED: 0 through 9.¹ The default for zlib is -1 which is equivalent to compression level 6. 0 means no compression and 9 is maximum compression.²</li><li>ZIP_BZIP2: 1 through 9¹, where the default level is 9.³</li><li>ZIP_LZMA: This has no effect¹ and no compression level is given to the compressor as seen in the source code⁶. However, the LZMA documentation states that it takes a compression level from 0 through 9 where 6 is the default.⁴</li><li>ZIP_ZSTANDARD: -131072 through 22 are accepted.¹ Where 20 is best compression for zstd⁵.</li></ul><h3>To conclude</h3><p>If you don’t want to make my mistake, set a compression method when you use Python’s zipfile module to create a ZipFile.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: <a href="https://github.com/UnicornOnAzur/">https://github.com/UnicornOnAzur/.</a></blockquote><p>[1] https://docs.python.org/3/library/zipfile.html</p><p>[2] https://docs.python.org/3/library/zlib.html#module-zlib</p><p>[3] https://docs.python.org/3/library/bz2.html#module-bz2</p><p>[4] https://docs.python.org/3/library/lzma.html#module-lzma</p><p>[5] https://docs.python.org/3/library/compression.zstd.html#module-compression.zstd</p><p>[6] https://github.com/python/cpython/blob/3.14/Lib/zipfile/__init__.py#L863</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c9a8dd0a95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/dont-forget-to-deflate-your-files-while-zipping-them-a-tip-for-using-python-s-zipfile-40c9a8dd0a95">Don’t forget to deflate your files while zipping them: a tip for using Python’s ZipFile.</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to choose the color palette for your next Streamlit app?]]></title>
            <link>https://medium.com/top-python-libraries/how-to-choose-the-color-palette-for-your-next-streamlit-app-b378adf689c5?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/b378adf689c5</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-control-flow]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[streamlit-app-development]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 08:43:55 GMT</pubDate>
            <atom:updated>2026-07-31T07:22:01.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to choose the color palette for your next Streamlit app? Seven nifty tricks for Streamlit behind building an interactive color demonstrator.</h3><p>Changing the theme, resetting widgets, checking the runtime environment and more…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_x3xPhcCGc8FpKM2TXMBjg.jpeg" /><figcaption>Image created with Magicstudio</figcaption></figure><p>After creating ten Streamlit apps, I never quite got the hang of picking a nice color palette or matching brand colors. Part of the struggle was the hassle of editing the config file, restarting the app, checking the colors, and going through that cycle until it looked good. Recently, I discovered a method to create an interactive color demo. This led me to develop this app (<a href="https://colorpickerdemo.streamlit.app/">link</a>) that showcases six awesome tricks with Streamlit I’ll explain.</p><ol><li>Dynamically changing the colors on a Streamlit app;</li><li>Dynamically arrange widgets into columns;</li><li>Resetting a file uploader widget;</li><li>Creating a form;</li><li>Update widget values within a form;</li><li>Check the runtime environment;</li><li>Run setup once.</li></ol><h3>Being handy with Streamlit</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52888093384d7b995b765d9d1dd5f9e7/href">https://medium.com/media/52888093384d7b995b765d9d1dd5f9e7/href</a></iframe><p>This MWE to interactively change the colors is this Streamlit form that you could paste into (the sidebar of) your app you are developing and see the results of changing the color. I’ll go into a bit more detail on the full-fledged demonstrator I built.</p><h4>1. Dynamically changing the colors on an app</h4><p>The theme, including the colors, of a Streamlit app are set using the config.toml file that is placed in the .streamlit folder.¹ Under the theme header the colors can be set.² There are six color fields that form the basis for the displayed color palette. I’ll summarize the Streamlit documentation below:</p><ul><li>primaryColor defines the accent color most often used throughout your Streamlit app. The following features and effects use your primary color:<br>○ Button hover effects,<br>○ Elements in focus<br>○ Selected elements.³</li><li>backgroundColor defines the background color of your app³, not including the sidebar.</li><li>secondaryBackgroundColor is used for contrast in the following places:<br>○ The background of input or selection regions for widgets;<br>○ Headers within elements like st.help and st.dataframe;<br>○ Code blocks and inline code.³</li><li>textColor sets the default text color for all text in the app except language-highlighting in code blocks, inline code, and links.³</li><li>linkColor sets the default font color for all Markdown links in the app.³</li><li>borderColor set the border color for:<br>○ Containers with borders, including expanders, forms, dialogs, popovers, and toasts,<br>○ The sidebar, including the right edge and the boundary below the navigation menu,<br>○ Dataframes and tables, <br>○ st.tabs (bottom border), <br>○ Buttons, including st.button, st.pills, and st.segmented_control<br>○ Borders on input regions³.</li></ul><p>A few widgets use colors that can be set separately such as st.badge, or are set to a default color such as st.success, st.info, st.warning, st.error and st.exception.</p><p>In my demonstrator I read in the current colors from the config.toml in the Session State and from there into the color picker widgets. Changes to the colors are written to the config.toml file and then on the rerun the colors are updated.</p><p>Here is a config.toml you can take for inspiration: <a href="https://github.com/jmedia65/awesome-streamlit-themes/blob/main/cyberpunk/.streamlit/config.toml">github</a>.</p><h4>2. Dynamically arrange widget</h4><p>Using a custom decorator, you can position a widget in the next spot in a row, allowing multiple widgets to be arranged in rows after rows. Below is the code for the decorator I made to dynamically arrange widgets in a variable number of columns.</p><pre>import functools<br>import streamlit as st<br><br>def set_widget_in_columns(number_of_columns=2):<br>    def decorator(func):<br>        @functools.wraps(func)<br>        def wrapper(*args):<br>            name, page_segment = args<br>            if not wrapper.columns:<br>                wrapper.columns = page_segment.columns(number_of_columns)<br>            widget = func(name, wrapper.columns[wrapper.count % number_of_columns])<br>            wrapper.count += 1<br>            return widget<br>        <br>        wrapper.count = 0<br>        wrapper.columns = []<br>        return wrapper<br>    <br>    return decorator</pre><p>The set_widget_in_columns function takes an integer parameter number_of_columns, which specifies how many columns to create for the widgets. The decorator function wraps the original function, allowing it to manage the layout of widgets. It initializes two attributes on the wrapper function⁴:</p><ul><li>wrapper.count: This keeps track of how many widgets have been created.</li><li>wrapper.columns: This stores the column layout generated by Streamlit.</li></ul><p>The wrapper function checks if the wrapper.columns list is empty, and if so, it initializes it with the specified number of columns. Each time a widget is created, it uses the modulo operator to determine which column to place the widget in, ensuring that widgets are distributed evenly across the columns. The function to create the widget is then called with the current column.</p><h4>3. Resetting a file uploader</h4><p>Since I made the file uploader read the input on change, I needed a way to prevent the app keep reapplying the input in a loop. Therefore, I reset the file uploader after having processed the input. Here is a MWE of how I reset the widget:</p><pre>uploaded_file = st.file_uploader(<br>    &quot;Upload a file&quot;, key=f&quot;uploader_key_{st.session_state.unique_key}&quot;)<br>if uploaded_file is not None:<br>    st.session_state.unique_key += 1<br>    st.rerun()</pre><p>I’ve gone into more detail on this and other options in this story:</p><p><a href="https://medium.com/top-python-libraries/resetting-the-streamlit-file-uploader-cd6ce133283a">Resetting the Streamlit File Uploader</a></p><h4>4. Creating a form</h4><p>To allow you to change all the colors and have the changes handle in batch, I put the color picker widgets in a form. Creating a form is an easy feat, but you need to mind the correct combination of storing the widget results and calling the callback function (for more see my story below). Because the widgets have an associated key there results are stored in the Streamlit Session State. When combined with the on_click parameter this makes for a very dense code block for the form. The great thing about this approach is you don’t need interim variables to store the selected colors before they are applied.</p><pre>import streamlit as st<br><br>form = st.form(&quot;form&quot;)<br>for field in COLOR_FIELDS:<br>    st.color_picker(label=field, key=field)<br>form.form_submit_button(on_click=write_session_state_to_toml)</pre><p><a href="https://medium.com/top-python-libraries/how-not-to-create-a-responsive-form-in-streamlit-d487bb0836a1">How (not) to create a responsive form in Streamlit?</a></p><h4>5. Update widget values within a form</h4><p>To get the colors in the color picker widgets updated after selecting a new color and, the case of my app, have them updated when the values in the Session State are changed, the widgets need to have a key associated with them. You do not need to set the value because that is retrieved via the key.</p><pre>st.color_picker(label=field, key=field)</pre><h4>6. Runtime environment</h4><p>I needed a different directory path when my app runs locally then when it runs on Streamlit Cloud. One way to work around this</p><pre>import streamlit as st<br><br>def is_app_running_locally():<br>    return st.context.url.startswith(&quot;http://localhost&quot;)</pre><p><a href="https://medium.com/top-python-libraries/where-is-this-streamlit-app-running-how-to-check-the-runtime-environment-of-a-streamlit-22382c63d2e9">Where is this Streamlit app running: How to check the runtime environment of a Streamlit?</a></p><h4>7. Run setup once</h4><p>Even though it isn’t necessary given how little setup is done, I’ve tried to isolate the setup in a function, determine_path, that is cached to prevent it being rerun when the app does.⁵</p><pre>def is_app_running_locally() -&gt; bool:<br>    return st.context.url.startswith(&quot;http://localhost&quot;)<br><br><br>@lambda _: _()<br>@st.cache_data()<br>def determine_path():<br>    folder_path: str = &quot;&quot; if is_app_running_locally() else\<br>        &quot;**/*streamlit-color-picker*/&quot;<br>    toml_file_path: str = next(glob.iglob(f&quot;{folder_path}.streamlit/*.toml&quot;,<br>                                          recursive=True))<br>    text_file_path: str = next(glob.iglob(f&quot;{folder_path}default.txt&quot;,<br>                                          recursive=True))<br>    import os; os.write(1, b&quot;called\n&quot;)<br>    return folder_path, toml_file_path, text_file_path<br><br><br>FOLDER_PATH, TOML_FILE_PATH, TXT_FILE_PATH = determine_path</pre><p>To get the function to run immediately I turned it into an IIFE using the @lambda _: _() decorator. This is something I explored earlier in this story.</p><p><a href="https://medium.com/pythoneers/using-an-iife-and-query-parameters-with-streamlit-taking-a-popular-thing-from-javascript-and-look-f82f50a40070">Using an IIFE and query parameters with Streamlit: taking a popular thing from Javascript and look…</a></p><h3>To conclude</h3><p>It is a great feeling to see so many little tricks and handy approaches come together in this demonstrator. Although some of the solutions took quite some time to figure out, I am really pleased that was able to (re-)use or work them into this app. All in all it was a funny experience to grow from getting a color picker to work on a config file until I hodgepodge of elements on an app that are able to interactively show the effects of changing that file.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: <a href="https://github.com/UnicornOnAzur/">https://github.com/UnicornOnAzur/</a>.</blockquote><p>[1] <a href="https://docs.streamlit.io/develop/concepts/configuration/theming">https://docs.streamlit.io/develop/concepts/configuration/theming</a></p><p>[2] <a href="https://docs.streamlit.io/develop/api-reference/configuration/config.toml#theme">https://docs.streamlit.io/develop/api-reference/configuration/config.toml#theme</a></p><p>[3] <a href="https://docs.streamlit.io/develop/concepts/configuration/theming-customize-colors-and-borders">https://docs.streamlit.io/develop/concepts/configuration/theming-customize-colors-and-borders</a></p><p>[4] <a href="https://www.pythonmorsels.com/storing-attributes-on-functions-in-python/">https://www.pythonmorsels.com/storing-attributes-on-functions-in-python/</a></p><p>[5] <a href="https://docs.streamlit.io/develop/concepts/architecture/caching">https://docs.streamlit.io/develop/concepts/architecture/caching</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b378adf689c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/how-to-choose-the-color-palette-for-your-next-streamlit-app-b378adf689c5">How to choose the color palette for your next Streamlit app?</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How (not) to create a responsive form in Streamlit?]]></title>
            <link>https://medium.com/top-python-libraries/how-not-to-create-a-responsive-form-in-streamlit-d487bb0836a1?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/d487bb0836a1</guid>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[session-state]]></category>
            <category><![CDATA[python-control-flow]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 12:41:31 GMT</pubDate>
            <atom:updated>2026-07-20T12:41:31.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Diving into the limitations of st.form, or when does st.form not perform as responsively as expected?</p><p>With the addition of st.form¹, Streamlit’s user experience has improved significantly. While I was building an app recently, I discovered an “anti-pattern” regarding the use of callback functions with inputs from st.form. When the form is submitted, the most recent values are not updated yet, and you need to press the button twice. I’m not the first to encounter this (<a href="https://discuss.streamlit.io/t/form-submit-button-does-get-latest-values-on-click/19558">see here</a>, <a href="https://discuss.streamlit.io/t/date-input-not-working-on-form-submit/34740">here</a> or <a href="https://discuss.streamlit.io/t/streamlit-form-button-has-to-be-clicked-twice/36690">here</a>). That’s why I’m sharing this story for future reference and to help others learn from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozeQxHAjvhiccTYn80mUaQ.jpeg" /><figcaption>Image created by magicstudio</figcaption></figure><h3>When doesn’t it work?</h3><p>If you create a basic form and want to use the results in your callback function, in the setup below you’ll encounter that the variables are not updated before the submit button is pressed. The MWE shown below will show you that your selection is not shown when you press the button the first time. Only on the second press of the button is the updated value shown.</p><pre>import streamlit as st<br><br>with st.form(&quot;form&quot;):<br>    s = st.segmented_control(&quot;Slide&quot;, options=range(5))<br>    st.form_submit_button(&quot;Submit&quot;, on_click=st.write, args=(s, ))</pre><p>So why doesn’t it work? Apparently when storing the output of widgets in variables these are not updated when the submit button is pressed.²’³’⁴</p><p>A simple change to using the Session State will make it work.</p><pre>import streamlit as st<br><br><br>def callback(key: str):<br>    st.write(st.session_state[key])<br><br><br>with st.form(&quot;form&quot;):<br>    st.segmented_control(&quot;Slide&quot;, options=range(5), key=&quot;s&quot;)<br>    st.form_submit_button(&quot;Submit&quot;, on_click=callback, args=(&quot;s&quot;))</pre><h3>What works?</h3><p>To show what works I’ve look at the options/choices you can make when created a form:</p><ul><li>Using the with statement or the direct assignment;</li><li>Using variables or keys for the output;</li><li>Using a callback function, via on_click, or a function called on an if-statement³.</li></ul><p>This gives eight possible combinations to make a form. In <a href="https://formdemo1.streamlit.app/">this app</a> I showcase how all combinations work as long as the widget state is not stored in a variable together with on_click. In essence, the options for forms mentioned in the documentation³’⁵ work.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: <a href="https://github.com/UnicornOnAzur/">https://github.com/UnicornOnAzur/</a>.</blockquote><p>[1] <a href="https://discuss.streamlit.io/t/introducing-submit-button-and-forms/12401">https://discuss.streamlit.io/t/introducing-submit-button-and-forms/12401</a></p><p>[2] <a href="https://discuss.streamlit.io/t/date-input-not-working-on-form-submit/34740/6">https://discuss.streamlit.io/t/date-input-not-working-on-form-submit/34740</a></p><p>[3] <a href="https://docs.streamlit.io/develop/api-reference/execution-flow/st.form">https://docs.streamlit.io/develop/api-reference/execution-flow/st.form</a></p><p>[4] <a href="https://discuss.streamlit.io/t/using-form-submit-button-with-callback-does-not-capture-arg-from-other-form-input/81134">https://discuss.streamlit.io/t/using-form-submit-button-with-callback-does-not-capture-arg-from-other-form-input/81134</a></p><p>[5] <a href="https://docs.streamlit.io/develop/concepts/architecture/forms">https://docs.streamlit.io/develop/concepts/architecture/forms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d487bb0836a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/how-not-to-create-a-responsive-form-in-streamlit-d487bb0836a1">How (not) to create a responsive form in Streamlit?</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resetting the Streamlit File Uploader]]></title>
            <link>https://medium.com/top-python-libraries/resetting-the-streamlit-file-uploader-cd6ce133283a?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd6ce133283a</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-control-flow]]></category>
            <category><![CDATA[python-app-development]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 12:38:03 GMT</pubDate>
            <atom:updated>2026-07-19T12:38:03.209Z</atom:updated>
            <content:encoded><![CDATA[<p>How can you remove the files from st.file_uploader without have to do this manually?</p><p>Sometimes, you might want your Streamlit app to automatically remove uploaded files from the st.file_uploader. This is especially useful when you’re running heavy computations on the input, as it can slow down your app or lead to unnecessary work. While there isn’t a standard method in the Streamlit documentation yet, there are two main options to consider. After reviewing numerous discussions and issues on the Streamlit forum, which I’ve linked at the end of this article, I’ve summarized these two key options and included an additional potential solution. You can check out this app, <a href="https://reset-file-uploader.streamlit.app/,">https://reset-file-uploader.streamlit.app/,</a> which showcases all these options, and this article serves as a placeholder for any future solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNi8g5qnZrOexlULXQxFEQ.jpeg" /><figcaption>Image created with MagicStudio</figcaption></figure><h3>Ways to reset the file uploader</h3><p>There are two ways to reset the st.file_uploader, by changing the unique key of the widget and by using the clear_on_submit when used within a st.form.</p><h4>1. Resetting the key</h4><blockquote>As long as the widget identity remains the same and that widget is continuously rendered on the frontend, then it will be stateful and remember user input.²</blockquote><p>The first approach is changing the key assigned to the widget. This changes the identity and makes it forget user input i.e. clearing the input. The key of the st.file_uploader is changed by having an incrementing number add to the key after every upload. key=f”uploader_key_{st.session_state.unique_key}” creates the new key and the value unique_key is incremented.</p><p><strong>1a Using </strong><strong>st.rerun</strong></p><p>A variant is calling st.rerun() which reruns the app, changes the key and thus clears the input.</p><pre>uploaded_file = st.file_uploader(<br>    &quot;Upload a file&quot;, key=f&quot;uploader_key_{st.session_state.unique_key}&quot;)<br>if uploaded_file is not None:<br>    st.session_state.unique_key += 1<br>    st.rerun()</pre><p><strong>1b Using user interaction</strong></p><p>Another way to trigger a rerun is by having another widget interaction³, for example with a button click.</p><pre>uploaded_file = st.file_uploader(<br>    &quot;Upload a file&quot;, key=f&quot;uploader_key_{st.session_state.unique_key}&quot;)<br>if uploaded_file is not None:<br>    st.session_state.unique_key += 1<br>right.button(&quot;Click&quot;)</pre><p><strong>1c. using </strong><strong>on_change</strong></p><p>Something I haven’t seen yet but that does work is using the on_change parameter. After your uploaded file has been handled, the unique_key is incremented and on the following rerun the st.file_uploader is reset.</p><pre>def callback():<br>    # Do something<br>    st.session_state.unique_key += 1<br><br>st.file_uploader(<br>    &quot;Upload a file&quot;, key=f&quot;uploader_{st.session_state.unique_key}&quot;,<br>    on_change=callback)</pre><h4>2. Using clear_on_submit</h4><p>A completely different approach is using and resetting the widget within a st.form. With the clear_on_submit parameter of the form, all widgets, including the uploader, are cleared.</p><pre>form = st.form(&quot;form&quot;, clear_on_submit=True)<br>form.file_uploader(&quot;Upload a file&quot;)<br>form.form_submit_button()</pre><h3>To conclude</h3><p>In the end, resetting or clearing this widget isn’t that difficult. Hopefully this story contribute to some MWE of how to do so.</p><blockquote><em>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: </em><a href="https://github.com/UnicornOnAzur/"><em>https://github.com/UnicornOnAzur/</em></a><em>.</em></blockquote><p>[1] <a href="https://docs.streamlit.io/develop/api-reference/widgets/st.file_uploader">https://docs.streamlit.io/develop/api-reference/widgets/st.file_uploader</a></p><p>[2] <a href="https://docs.streamlit.io/develop/concepts/architecture/widget-behavior">https://docs.streamlit.io/develop/concepts/architecture/widget-behavior</a></p><p>[3] <a href="https://docs.streamlit.io/develop/concepts/architecture/fragments">https://docs.streamlit.io/develop/concepts/architecture/fragments</a></p><ol><li>June 2021, “<a href="https://discuss.streamlit.io/t/clear-the-cache-for-file-uploder-on-streamlit/14304">Clear the cache for file uploder on streamlit</a>”</li><li>August 2021, “<a href="https://github.com/streamlit/streamlit/issues/3684">Add form.clear() to the API</a>”</li><li>November 2022, “<a href="https://discuss.streamlit.io/t/file-uploader-how-to-clear-the-list-of-uploaded-files/32729">File_uploader — How to clear the list of uploaded files?</a>”</li><li>April 2023, “<a href="https://discuss.streamlit.io/t/are-there-any-ways-to-clear-file-uploader-values-without-using-streamlit-form/40903">Are there any ways to clear file uploader values without using streamlit form</a>”</li><li>May 2023, “<a href="https://github.com/streamlit/streamlit/issues/6748">Uploaded file not removed even upon app refresh</a>”</li><li>Jule 2023, “<a href="https://discuss.streamlit.io/t/clear-st-file-uploader-without-using-st-form/47276">Clear st.file_uploader without using st.form</a>”</li><li>Jule 2023, “<a href="https://discuss.streamlit.io/t/how-to-remove-the-uploaded-file-in-streamlit-when-clicking-on-the-self-made-reset-all-streamlit-button/47260">How to remove the uploaded file in Streamlit when clicking on the self-made “Reset all” streamlit button?</a>”</li><li>January 2024, “<a href="https://discuss.streamlit.io/t/clear-file-after-use-file-uploader/60011">Clear file after use file_uploader</a>”</li><li>April 2024, “ <a href="https://discuss.streamlit.io/t/clear-the-file-uploader-after-using-the-file-data/66178">Clear the file_uploader after using the file data</a>”</li><li>August 2025, “<a href="https://github.com/streamlit/streamlit/issues/12317">Add a “clear all” button to file uploader</a>”</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd6ce133283a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/resetting-the-streamlit-file-uploader-cd6ce133283a">Resetting the Streamlit File Uploader</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where is this Streamlit app running: How to check the runtime environment of a Streamlit?]]></title>
            <link>https://medium.com/top-python-libraries/where-is-this-streamlit-app-running-how-to-check-the-runtime-environment-of-a-streamlit-22382c63d2e9?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/22382c63d2e9</guid>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[runtime]]></category>
            <category><![CDATA[python-standard-library]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 12:37:52 GMT</pubDate>
            <atom:updated>2026-07-19T12:37:52.692Z</atom:updated>
            <content:encoded><![CDATA[<p>Multiple ways to check whether the current Streamlit app is running locally or not.</p><p>For those times you want to know if your Streamlit app is run locally. Currently, Streamlit doesn’t have a specific environment variable for this. There are some approaches to do so. I tested them and wrote them into functions for you to use. Each function will return True if the app is ran locally. Here is a demo app (<a href="https://demo-check-environment.streamlit.app/">link</a>) that shows the outcome of the checks and their original value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQqC9Vdu93GQn9tBWFrmmw.jpeg" /><figcaption>Image created with MagicStudio.com</figcaption></figure><h3>Checking the runtime environment</h3><p>The first option are three ways by using the Streamlit library, followed by two options from the Python Standard Library, and an approach I couldn’t get to work.</p><h4>1. Using Streamlit</h4><p>The first and easiest way to check if your app is running through localhost is by comparing the URL through which the user is accessing the app. Since Streamlit 1.45.0 this can be done with the st.context.¹</p><pre>import streamlit as st<br><br>def is_app_running_locally():<br>    return st.context.url.startswith(&quot;http://localhost&quot;)</pre><p>As can be seen in the source code the above attribute is a wrapper around the get_script_run_ctx function.² This returns a ScriptRunContext object that contains a ContextInfo where the URL is stored. Apart from cleaning up the path in the wrapper this results in the similar URL.</p><pre>import streamlit.runtime.scriptrunner_utils.script_run_context as run_context<br><br>def is_app_running_locally():<br>    context: run_context.ScriptRunContext = run_context.get_script_run_ctx()<br>    return &quot;http://localhost&quot; in context.context_info.url</pre><p>The ScriptRunContext object is one part of the objects and layers created at runtime for an app. During execution three layers are created with corresponding objects.³ Another object that can help us is the Runtime object that stores a path where the script is run from. This path begins with a letter drive on a computer and mount on Streamlit Cloud.</p><pre>import streamlit as runtime<br>def is_app_running_locally():<br>    runtime_instance = runtime.Runtime.instance()<br>    return not runtime_instance._main_script_path.startswith(&quot;/mount/&quot;)</pre><h4>2. OS</h4><p>The first option using the Python Standard Library is with the os module. Through the getenv function we can access environment variables.⁴ There are at least three variables that are not set locally but are on Streamlit Cloud: USER, STREAMLIT_SERVER_RUN_ON_SAVE, and STREAMLIT_SERVER_ALLOW_RUN_ON_SAVE.⁵ So you can check whether they are None or a more explicit check to see of if they are not the value you expect.</p><pre>import os<br>def is_app_running_locally():<br>    return os.getenv(&quot;USER&quot;) != &quot;appuser&quot;</pre><h4>3. Platform</h4><p>Another approach is getting the processor name⁶, using the platform module⁷, where a non-empty string indicates a locally run app. However, because of the way the function handles an unsuccessful lookup it is not completely deterministic.</p><blockquote>An empty string is returned if the value cannot be determined.⁷</blockquote><pre>import platform<br>def is_app_running_locally():<br>    return platform.processor() != &quot;&quot;</pre><h4>4. Threading</h4><p>Finally, I found a Github gist⁸ that accesses the current thread. Although, using that didn’t give me an unique result, going through the documentation for the threading module⁹ I came up with something that works. The name attribute is the one set here.¹⁰</p><pre>import threading<br>def is_app_running_locally():<br>    return threading.current_thread().name.startswith(&quot;ScriptRunner&quot;)</pre><h3>To conclude</h3><p>Checking and trying to understand these six approaches was a nice way to get a slightly better understanding of how a Streamlit app works under the hood. Also, I got some approaches to check the runtime environment. It will need some validation in the actual environment you use but the ideas are here.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: <a href="https://github.com/UnicornOnAzur/">https://github.com/UnicornOnAzur/</a>.</blockquote><p>[1] <a href="https://docs.streamlit.io/develop/api-reference/caching-and-state/st.context#contexturl">https://docs.streamlit.io/develop/api-reference/caching-and-state/st.context#contexturl</a></p><p>[2] <a href="https://github.com/streamlit/streamlit/blob/fd19fcbdc1de26502538bfa9aa05963201821e3f/lib/streamlit/runtime/context.py#L345">https://github.com/streamlit/streamlit/blob/fd19fcbdc1de26502538bfa9aa05963201821e3f/lib/streamlit/runtime/context.py#L345</a></p><p>[3] <a href="https://deepwiki.com/streamlit/streamlit/3.3-script-execution-and-runtime">https://deepwiki.com/streamlit/streamlit/3.3-script-execution-and-runtime</a></p><p>[4] <a href="https://docs.python.org/3/library/os.html">https://docs.python.org/3/library/os.html</a></p><p>[5] <a href="https://discuss.streamlit.io/t/environment-variable-indicating-my-app-is-running-on-streamlit-sharing/8668/3">https://discuss.streamlit.io/t/environment-variable-indicating-my-app-is-running-on-streamlit-sharing/8668/3</a></p><p>[6] <a href="https://discuss.streamlit.io/t/check-if-run-local-or-at-share-streamlit-io/11841">https://discuss.streamlit.io/t/check-if-run-local-or-at-share-streamlit-io/11841</a></p><p>[7] <a href="https://docs.python.org/3/library/platform.html#module-platform">https://docs.python.org/3/library/platform.html#module-platform</a></p><p>[8] <a href="https://gist.github.com/tvst/f6ab192d4952757959f026007aadef6a">https://gist.github.com/tvst/f6ab192d4952757959f026007aadef6a</a></p><p>[9] <a href="https://docs.python.org/3/library/threading.html">https://docs.python.org/3/library/threading.html</a></p><p>[10] github.com/streamlit/streamlit/blob/a606eeca83d2810e9f81c57a3414ade0b3f5e954/lib/streamlit/runtime/scriptrunner/script_runner.py#L344</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22382c63d2e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/where-is-this-streamlit-app-running-how-to-check-the-runtime-environment-of-a-streamlit-22382c63d2e9">Where is this Streamlit app running: How to check the runtime environment of a Streamlit?</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Your Coding: Python Decorator Templates]]></title>
            <link>https://medium.com/top-python-libraries/simplify-your-coding-python-decorator-templates-e64df8c6c7a1?source=rss-6f9dea21fd41------2</link>
            <guid isPermaLink="false">https://medium.com/p/e64df8c6c7a1</guid>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-decorators]]></category>
            <category><![CDATA[python-standard-library]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[UnicornOnAzur]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 00:24:51 GMT</pubDate>
            <atom:updated>2026-04-12T00:24:51.889Z</atom:updated>
            <content:encoded><![CDATA[<p>Templates for function, method and class decorators.</p><p>I’ll let others, like @Abhid004 (<a href="https://medium.com/python-in-plain-english/python-decorators-advanced-guide-ad2a77354ef6">here</a>), debate the merits of using decorators in Python. There are plenty of decorators and examples already available. But whenever I try to create or modify one, I often need to refer back to previous work or blogs to get the construction right. That’s why I’m creating Github gists with templates, which I’ll link in this story along with some explanations on how they’re built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rwgeAEUV900wcB4fH6Bwg.jpeg" /><figcaption>Image created with magicstudio.com</figcaption></figure><p>I’ll go through three steps: how to use a decorator, how to make a decorator (the templates), and where to find the documentation.</p><h3>Using a decorator</h3><p>There are three things that can be decorated: a function, a class and a method.</p><h4>Decorating a function</h4><p>The most common use of decorators is on functions¹’². Examples are:</p><ul><li>The functools.wraps decorator: a decorator that is used in decorators to preserve the metadata of the original function³;</li></ul><pre>import functools<br><br>def decorator(func):<br>    @functools.wraps(func)<br>    def wrapper_decorator(*args, **kwargs):<br>        value = func(*args, **kwargs)<br>        return value<br>    return wrapper_decorator</pre><ul><li>The save_folium decorator I used for this story is an example of a decorator with arguments;</li></ul><p><a href="https://medium.com/pythoneers/how-to-center-and-zoom-to-your-geojson-in-geopandas-plotly-and-folium-3fe3fd9c0d54">How to center and zoom to your GeoJSON in GeoPandas, Plotly and Folium.</a></p><ul><li>The various use of decorators in Flask (see <a href="https://flask.palletsprojects.com/en/stable/quickstart/">tutorial</a>).</li></ul><h4>Decorating a method</h4><p>Since methods are essentially functions that are associated with a class they too can be decorated². Examples of these decorators are:</p><ul><li>The staticmethod decorator⁴ transforms <em>a method into a static method </em>(a method defined inside a class that does not depend on any instance or class data);</li></ul><pre>class C:<br>    @staticmethod<br>    def f(arg1, arg2, argN): ...</pre><ul><li>The classmethod decorator⁵ transforms <em>a method into a class method</em> (method that is bound to the class and not to an instance of the class);</li></ul><pre>class C:<br>    @classmethod<br>    def f(cls, arg1, arg2): ...</pre><h4>Decorating a class</h4><p>The last possibility to decorate are classes.⁵ Examples are:</p><ul><li>the dataclass decorator⁶ creates a Data Class and generate .__init__(), .__repr__(), and .__eq__() automatically;</li></ul><pre>from dataclasses import dataclass<br><br>@dataclass<br>class InventoryItem:<br>    &quot;&quot;&quot;Class for keeping track of an item in inventory.&quot;&quot;&quot;<br>    name: str<br>    unit_price: float<br>    quantity_on_hand: int = 0<br><br>    def total_cost(self) -&gt; float:<br>        return self.unit_price * self.quantity_on_hand</pre><p>If you know any other good examples, please share them in the comments.</p><h3>Making a decorator: the templates</h3><p>There are two kinds of decorators: those created from a function and those made from a class. Each type can either have parameters or not which makes four possible templates.</p><p><strong>1. A decorator function without arguments</strong></p><p>First, the template for a decorator of function that itself does not take any arguments. The basic setup of a decorator is a function with an inner function that takes the to be decorated function as a parameter. The inner function is returned by the outer function.⁷</p><pre>def decorator():<br>    def wrapper(func):<br>        func()<br>    return wrapper<br><br>@decorator<br>def decorated_function():<br>    pass<br># is equal to<br>decorated_function = decorator(decorated_function)</pre><p>The outer function, called decorator, takes in the argument func, which is the function that needs decoration. The inner function, known as wrapper, handles the positional and keyword arguments for that function. There are four different code blocks, numbered in the order they are executed, where you can achieve the desired effect of the decorator. To ensure that the metadata of the original function remains available functools.wraps is applied to func.³</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba3524d27dc12f6a696c894a51754ea/href">https://medium.com/media/dba3524d27dc12f6a696c894a51754ea/href</a></iframe><p><strong>2. A decorator with arguments</strong></p><p>To accept arguments for the decorator an additional function is needed. The decorator function takes the parameter for the decorator. The inner_decorator accepts the to be decorated function, and the wrapper again accepts the positional and keyword arguments. This results in six code blocks to be used for the desired effect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f6eb72a79acdf1cd859d9c94174e432/href">https://medium.com/media/5f6eb72a79acdf1cd859d9c94174e432/href</a></iframe><p><strong>3. A decorator class without parameters</strong></p><p>To create a class that can be used as a decorator both the __init__ and __call__ method are needed. During initialization the to be decorated function is taken as an argument. During the call of the decorator the arguments to the function are taken in.⁸</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a08dde1acce8c52ad9b957448068830d/href">https://medium.com/media/a08dde1acce8c52ad9b957448068830d/href</a></iframe><p><strong>4. A decorator class with parameters</strong></p><p>A way to have the decorator accept parameters is to take in these in the __init__ method. The __call__ method is in essence a regular decorator without parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a124c033fab131387f8f92f3b41d16d5/href">https://medium.com/media/a124c033fab131387f8f92f3b41d16d5/href</a></iframe><h3>Documentation</h3><p>You can find the official documentation on decorators here:</p><ul><li><a href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a> — Decorators for Functions and Methods;</li><li><a href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong> </a>— Class Decorators;</li><li><a href="https://docs.python.org/3/reference/compound_stmts.html#function">Function definitions</a>;</li><li><a href="https://docs.python.org/3/reference/compound_stmts.html#class-definitions">Class definitions</a>;</li></ul><p>Additionally, these blogs/stories help explain how to use them:</p><ul><li><a href="https://realpython.com/primer-on-python-decorators/">Real Python</a>: Primer on Python Decorators;</li><li><a href="https://builtin.com/software-engineering-perspectives/python-class-decorator">Stephen Fordham</a>: Using Python Class Decorators;</li></ul><h3>To conclude</h3><p>Creating the templates helped be understand which code block could be used for which action. Furthermore, gathering the use and structure of the decorators in one place together with the templates has at least created a good reference for myself, and hopefully for you too.</p><blockquote>This story is my way to share my coding experience and the lessons I learned, and to document my solutions. All claps, comments, and highlights are appreciated, as well as sharing the story. For more code and my other links see: <a href="https://github.com/UnicornOnAzur/">https://github.com/UnicornOnAzur/</a>.</blockquote><p>[1] <a href="https://docs.python.org/3/reference/compound_stmts.html#function">https://docs.python.org/3/reference/compound_stmts.html#function</a></p><p>[2] <a href="https://peps.python.org/pep-0318/#current-implementation-history">https://peps.python.org/pep-0318/</a></p><p>[3] <a href="https://docs.python.org/3/library/functools.html#functools.wraps">https://docs.python.org/3/library/functools.html#functools.wraps</a></p><p>[4] <a href="https://docs.python.org/3/library/functions.html#staticmethod">https://docs.python.org/3/library/functions.html#staticmethod</a></p><p>[5] <a href="https://peps.python.org/pep-3129/">https://peps.python.org/pep-3129/</a></p><p>[6] <a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass">https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass</a></p><p>[7] <a href="https://realpython.com/primer-on-python-decorators/#decorating-classes">https://realpython.com/primer-on-python-decorators/</a></p><p>[8] <a href="https://builtin.com/software-engineering-perspectives/python-class-decorator">https://builtin.com/software-engineering-perspectives/python-class-decorator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e64df8c6c7a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/top-python-libraries/simplify-your-coding-python-decorator-templates-e64df8c6c7a1">Simplify Your Coding: Python Decorator Templates</a> was originally published in <a href="https://medium.com/top-python-libraries">Top Python Libraries</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>