<?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 Adarsh Divakaran on Medium]]></title>
        <description><![CDATA[Stories by Adarsh Divakaran on Medium]]></description>
        <link>https://medium.com/@adarshd?source=rss-e0535497e40------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q4XmHFG0rSA50KMmJTgwjQ.jpeg</url>
            <title>Stories by Adarsh Divakaran on Medium</title>
            <link>https://medium.com/@adarshd?source=rss-e0535497e40------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:00:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adarshd/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[Building an AI Agent in Python]]></title>
            <link>https://python.plainenglish.io/building-an-ai-agent-in-python-f70fdf6dfb18?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/f70fdf6dfb18</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 12:36:36 GMT</pubDate>
            <atom:updated>2026-06-04T12:36:36.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HF46bnmy2gE7WqBxobzu4Q.png" /></figure><p>2026 is shaping up to be a big year for AI agents. We are seeing more products where the AI not only answers a question but also does some work for the user.</p><p>You have probably used ChatGPT or a similar AI tool to answer a question, help with writing, or explain some code. You type something, the AI responds, and the conversation goes back and forth. That is powerful, but it is also limited. The AI is essentially stuck in a chat box — it can only talk to you; it cannot do anything on your behalf.</p><p>AI agents change that. An agent is an AI that can actually take actions — browse the web, read and write files, run code, call APIs, and more. It does not just answer your question; it works toward a goal, step by step, using whatever tools it needs. Tools like Lovable, Cursor, and Claude Code are examples of this in practice.</p><p>In this article, we will explore the concepts behind building an AI agent in Python. We will use the <a href="https://github.com/openai/openai-python">OpenAI Python SDK</a> (Responses API) for the examples, but the same ideas can be generalized to any other LLM SDK. We will use a low-level SDK with minimal abstractions so we can observe and implement most of the agent’s behavior on our end.</p><p><strong>TL;DR</strong></p><p>This tutorial explains how AI agents work by building a simple one in Python.</p><p>We will cover the core pieces: LLMs, prompts, context, memory, the agent loop, tools, MCP, and skills:</p><p><strong>LLM: </strong>Acts as the reasoning engine that understands the user request and decides what to do next.<br><strong>System prompt: </strong>Defines the agent’s role, behavior, boundaries, and response style.<br><strong>Context window: </strong>Controls how much information the model can see at once, including prompts, history, tool results, and files.<br><strong>Memory: </strong>Helps the agent remember useful information across steps or conversations.<br><strong>Agent loop: </strong>Repeats the process of thinking, acting, observing results, and deciding the next step.<br><strong>Tool calling: </strong>Lets the agent use external functions such as APIs, web search, file access, or code execution.<br><strong>MCP: </strong>Provides a standard way to connect agents to reusable tools and data sources.<br><strong>Skills: </strong>Package reusable instructions, workflows, examples, and scripts for specific tasks.</p><h3>What are Agents?</h3><p>An AI agent is an AI system that can autonomously plan and execute multi-step actions toward a goal.</p><p>To understand agents, it helps to first understand what is powering them under the hood — a large language model, or LLM. For example, ChatGPT is a product built on top of OpenAI GPT LLMs. When you type a message and get a response, an LLM is doing the heavy lifting. It takes text as input and generates text as output.</p><p>On their own, LLMs are impressive but limited. They can only respond with text. They cannot open your browser, read a file on your computer, or send an email. They also do not know what happened yesterday, because their knowledge comes from training data with a cutoff date, not a live connection to the world.</p><p>Agents fix this by giving LLMs access to tools. A tool is just a function your code exposes to the model — something like “search the web” or “read this file.” The model can decide to call a tool when it needs to, and your code actually runs it. This turns a passive text generator into something that can act.</p><p>A good way to see the difference is to compare using ChatGPT with using Claude Code for a coding task. With ChatGPT, you describe the problem, copy the suggested code, paste it into your editor, run it, copy the error back, and repeat. The model has no idea what is actually in your project. Claude Code is different — it is powered by an LLM but also has access to tools like bash and file reading. You describe what you want, and it reads your files, writes code, runs tests, and fixes errors on its own. You just watch and steer.</p><p>The simplest way to understand an agent is:</p><ol><li>The user gives a goal.</li><li>The model decides what step to take.</li><li>The agent runs that step using a tool.</li><li>The model looks at the result.</li><li>The process continues until the task is complete.</li></ol><p>This is different from a normal chatbot. A chatbot mainly responds. An agent can respond and act.</p><p>In a simple agent, the model may only call one tool and return the result. In a more capable agent, the model may make a plan, call multiple tools, observe the results, adjust the plan, and continue until the task is complete.</p><p>Before we build this kind of system, we need to choose the model that will drive it.</p><h3>LLMs</h3><p>LLMs are trained on massive amounts of text data — entire open source repositories on GitHub, books, articles, websites, and more. Through training, the model learns patterns in language well enough to generate coherent, useful responses. The scale of this training is what makes them surprisingly capable across such a wide range of tasks.</p><p>At their core, LLMs are text-in, text-out systems. You send them a block of text (called a prompt), and they generate a response. Everything that happens — reasoning, answering questions, writing code, making decisions — is expressed through that text interface. When an agent calls a tool, it is really the model writing out a structured text request, and your code intercepts that and actually runs the function.</p><p>The key limitation to keep in mind: LLMs only know what they were trained on. They have no awareness of events after their training cutoff and no way to look things up in real time unless they are given a tool to do so. This is part of what makes tools so valuable — they extend the model’s reach into the real world.</p><h3>Choosing an LLM</h3><p>For an AI agent, the LLM is its brain. The quality of the model affects how well the agent understands instructions, chooses tools, handles errors, and completes multi-step tasks.</p><p>At the same time, the most powerful model is not always the right choice. We also need to think about cost, speed, context window, reasoning ability, and where the model is hosted.</p><h3>Benchmarks</h3><p>Benchmarks are standardized tests used to compare the performance of different models. For coding tasks, there is <a href="https://www.swebench.com/">SWE-bench</a>. For general reasoning, there is <a href="https://www.kaggle.com/benchmarks/open-benchmarks/mmlu">MMLU</a>. Each benchmark tests the model on a specific type of problem and gives it a score. A higher score generally means the model will perform better on that type of task.</p><p>Benchmarks are a useful starting point when choosing a model, but they are not the whole story. A model that scores well on a benchmark may still behave unexpectedly in your specific use case, so it is always worth testing with your actual workload.</p><h3>Costs</h3><p>Choosing the best-scoring model from a benchmark may not always be the most intelligent decision.</p><p>Cost is a real factor, especially at scale. Most providers charge per token, which is the basic unit of text the model processes. A token is roughly four characters, or about three-quarters of a word on average. Both what you send to the model (input) and what it generates back (output) count toward your token usage.</p><p>For an agent that runs multiple steps in a loop, token usage adds up quickly. A good approach is to start with a capable model and then see if a smaller or cheaper one can do the same job well enough. Sometimes a smaller model handles simple tasks just fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7aYwnjM9D45f3XEi.png" /><figcaption>Model costs table from <a href="https://github.com/simonw/llm-prices">https://github.com/simonw/llm-prices</a></figcaption></figure><h3>Reasoning Level</h3><p>Some models are designed to think before they answer. These reasoning models break complex problems into smaller steps internally, often called reasoning traces. You can think of it as the model working through a scratchpad before writing its final response. This can improve performance for tasks that need planning, debugging, tool use, or careful decision-making.</p><p>More reasoning effort usually means higher cost, higher response time, and better accuracy for complex tasks.</p><p>Not every request needs high reasoning. If the task is simple, we can use a lower reasoning level or a cheaper model. If the task involves multiple steps, unknown errors, or important decisions, more reasoning can be useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ir5BWVBRa2ybcB5t.png" /><figcaption>Conversation with GPT-OSS LLM showing reasoning/thought traces</figcaption></figure><h3>Hosted vs Local</h3><p>Most people start with a hosted model — one that runs on a provider’s servers and is accessed via an API. These are easy to set up, well-maintained, and generally the most capable options available. The trade-off is that you pay per token, and your data is processed by a third party.</p><p>There are also open models that can run entirely on your own machine/server. They can avoid per-token API costs and give you more control over data. The downside is that they require capable hardware and are generally less powerful than the best hosted models today. That said, local models are getting better quickly. Previous generation frontier capabilities are being replicated in the next generation of local models, and this gap will continue to close. Examples of open-weight models that can be self-hosted, depending on hardware and quantization, include <a href="https://deepmind.google/models/gemma/gemma-4/">Gemma 4 series</a> and <a href="https://www.kimi.com/ai-models/kimi-k2-6">Kimi K2.6</a>.</p><p>There are already decent <a href="https://medium.com/google-cloud/i-ran-gemma-4-as-a-local-model-in-codex-cli-7fda754dc0d4">local coding models that people use</a> for simple code generation and verification. In the coming years, this will improve, and stronger models will become available on consumer devices.</p><p>Hosted models are still easier to use for many applications. They usually provide better quality, higher reliability, larger context windows, and managed infrastructure.</p><p>Local models give more control over data, cost, and deployment. But they also require more setup, hardware, monitoring, and optimization.</p><h3>Configuring the LLM</h3><p>Once you have picked a model, there are two things you set up before the agent starts running: the system prompt and the context window.</p><h3>System Prompt</h3><p>A system prompt is the model’s top-level instruction that guides its behavior during a conversation.</p><p>It can set rules such as:</p><ul><li>what role the AI should play</li><li>what tone it should use</li><li>what it should or should not do</li><li>how it should handle tools</li><li>how it should handle safety and user requests</li><li>how it should format the final answer</li></ul><p>For an agent, the system prompt is very important. It tells the model how to behave while using tools. It can also define boundaries, such as asking for permission before destructive actions or avoiding actions outside the user’s request.</p><p>Let’s see an example of this in practice:</p><pre>import os<br><br>if __name__ == &#39;__main__&#39;:<br>    from openai import OpenAI<br><br>    client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>    response = client.responses.create(<br>        model=&quot;gpt-5.4-mini&quot;,<br>        input=[<br>            {<br>                &quot;role&quot;: &quot;system&quot;,<br>                &quot;content&quot;: &quot;You are a friendly Python tutor. Refuse all requests unrelated to Python coding&quot;,<br>            },<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: input(&quot;Enter your Python question: &quot;),<br>            },<br>        ],<br>    )<br><br>    print(response.output_text)</pre><p>In the above script, we initialize an OpenAI client and use client.responses.create to send a message to gpt-5.4-mini model. The system prompt is specified in the input list as the first entry. &quot;role&quot;: &quot;system&quot; designates the entry as the system prompt. In the above example, the model is instructed to act as a Python tutor and refuse requests unrelated to Python. As the next entry, we accept the user prompt via input() and pass it to the LLM for answering.</p><p>If the script is run and any unrelated queries are passed to the LLM, we get a refusal response similar to the one below:</p><pre>Enter your Python question: How many states are there in the US?</pre><pre>Model response: I’m here to help with Python coding questions only. If you have a Python-related question, feel free to ask!</pre><p>Even though the underlying large language model knows the answer to the user’s query, it refuses to answer as per the direction in the system prompt.</p><h3>Context Window</h3><p>The context window is the model’s working memory. It is the amount of information the model can see in one request.</p><p>The context can include the user message, conversation history, system prompt, tool results, files, documentation, and any other information we provide.</p><p>Most of the latest flagship models support up to 1M tokens, which is roughly 750,000 words or about 15 books. Older models like GPT-4 series models had a 128K token window, around 2 books’ worth. For agents that run long tasks or work with large documents, context window size matters a lot. When the context fills up, older information gets dropped, which can cause the agent to lose track of earlier steps in a long task.</p><p>A larger context window is useful, but it is not free. More context usually means more cost and slower responses. Also, just because a model can accept a lot of context does not mean every token is equally important.</p><p>Good agents manage context carefully. They include what is needed, summarize old information, and avoid filling the context with unnecessary data.</p><p>Once we understand the model and its context window, the next question is what the agent should remember across steps and conversations.</p><h3>Memory</h3><p>Memory helps an agent remember useful information.</p><p>Short-term memory helps the agent remember what the user said earlier in the same conversation. This usually lives inside the context window.</p><p>Let’s consider an example. The snippet below accepts a user query inside a loop and sends it to a model to get the response:</p><pre>import os<br><br>if __name__ == &#39;__main__&#39;:<br><br>    from openai import OpenAI<br>    client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>    while True:<br>        user_query = input(&quot;You: &quot;)<br>        if user_query.lower() in [&quot;exit&quot;, &quot;quit&quot;]:<br>            break<br><br>        response = client.responses.create(<br>            model=&quot;gpt-5.4-mini&quot;,<br>            input=user_query,<br>        )<br><br>        assistant_reply = response.output_text<br>        print(f&quot;Model: {assistant_reply}&quot;)</pre><p>The code works, but there are issues:</p><pre>You: Tell me about Taj Mahal in 1 sentence<br>Model: The Taj Mahal is a magnificent white marble mausoleum in Agra, India, built by Emperor Shah Jahan in memory of his wife Mumtaz Mahal, and is one of the world&#39;s most famous symbols of love.</pre><pre>You: When was it built?<br>Model: I can help, but I need to know **what “it” refers to**.  <br>Please share the name, photo, or location of the building/structure/object, and I’ll tell you when it was built.</pre><p>As seen from the transcript, the model fails to answer the user’s follow-up prompt. This is because, we did not implement short term memory. For the model to be able to respond to follow-ups properly, we need to store and pass the conversation history to LLM calls. The snippet improves on the above script with short term memory implementation:</p><pre>import os<br><br>if __name__ == &#39;__main__&#39;:<br>    from openai import OpenAI<br><br>client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>conversation_history = []<br><br>while True:<br>    user_query = input(&quot;You: &quot;)<br><br>    if user_query.lower() in [&quot;exit&quot;, &quot;quit&quot;]:<br>        break<br><br>    conversation_history.append({<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: user_query,<br>    })<br><br>    response = client.responses.create(<br>        model=&quot;gpt-5.4-mini&quot;,<br>        input=conversation_history,<br>    )<br><br>    assistant_reply = response.output_text<br>    print(f&quot;Model: {assistant_reply}&quot;)<br><br>    conversation_history.append({<br>        &quot;role&quot;: &quot;assistant&quot;,<br>        &quot;content&quot;: assistant_reply,<br>    })<br></pre><p>We introduced a conversation_history list that stores previous messages. User messages are appended to this list with “role”: “user” and model responses are appended with “role”: “assistant”. This way, whenever a request is sent to the model, it gets the entire message history through the input argument and will be able to respond to follow-up prompts correctly.</p><pre>You: Tell me about Taj Mahal in 1 sentence<br>Model: The Taj Mahal is a stunning white marble mausoleum in Agra, India, built by Emperor Shah Jahan in memory of his wife Mumtaz Mahal<br><br>You: When was it built?<br>Model: It was built between 1632 and 1653.</pre><p>Long-term memory stores information beyond one conversation and persists even after the current chat or task ends. This is useful when you want the agent to remember user preferences, past decisions, or domain-specific facts across sessions. Common approaches include RAG (retrieval-augmented generation), where relevant information is fetched from a database and added to the context as needed, and built-in memory systems like ChatGPT Memories, where key facts are stored and automatically recalled in future conversations.</p><h3>Agent Loop</h3><p>The agent loop is the core flow of an agent.</p><p>A simple loop looks like this:</p><ol><li>User sends a message.</li><li>Agent adds the message to the conversation context.</li><li>Agent sends the context and system prompt to the LLM.</li><li>LLM decides what to do next.</li><li>If needed, the LLM calls a tool.</li><li>Agent runs the tool and sends the result back to the LLM.</li><li>LLM decides whether more steps are needed.</li><li>When done, the LLM generates the final response.</li><li>Agent sends the response to the user.</li></ol><p>This loop is what makes agents feel different from normal chatbots. A chatbot usually gives one response. An agent can act, observe, and continue.</p><p>In practice, the intermediate steps are where the interesting work happens. The model may call a tool, wait for the result, process that result, decide to call another tool, and keep going before it gives a final answer. The loop runs as many times as needed until the model decides the task is complete or the user stops it. This brings us to tools — what they are and how they actually work.</p><h3>Tool Calling</h3><p>Tools are external capabilities that the agent can use.</p><p>Tools (also called functions) let an AI agent do things beyond generating text. They can be used to take actions or get information.</p><p>Examples of tools:</p><ul><li>search the web</li><li>call an API</li><li>read files</li><li>edit files</li><li>run code</li><li>send emails</li><li>query a database</li><li>create calendar events</li></ul><p>The agent chooses a tool when needed. The tool has a name, a description, and input parameters. The model decides which tool to call and what arguments to pass.</p><p>Tool descriptions are important. If a tool description is unclear, the model may call it at the wrong time or pass the wrong input. We should describe tools in simple language and make their inputs strict.</p><p>Here is an important detail: the model does not run the tool itself. When it decides to use a tool, it outputs a structured request with the tool name and the arguments it wants to pass. Your code intercepts this, runs the actual function, and passes the result back to the model. The model then reads the result and decides what to do next. This back-and-forth between the model and your code is what makes the agent loop so powerful.</p><p>Let’s see an example of tool calling in action:</p><pre>import json<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>def get_weather(location):<br>    return {<br>        &quot;location&quot;: location,<br>        &quot;temperature&quot;: &quot;24 C&quot;,<br>        &quot;condition&quot;: &quot;Sunny&quot;,<br>        &quot;humidity&quot;: &quot;52%&quot;,<br>        &quot;wind&quot;: &quot;11 km/h&quot;,<br>    }<br><br>if __name__ == &#39;__main__&#39;:<br>    from openai import OpenAI<br><br>    client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>    tools = [<br>        {<br>            &quot;type&quot;: &quot;function&quot;,<br>            &quot;name&quot;: &quot;get_weather&quot;,<br>            &quot;description&quot;: &quot;Get the current weather for a destination.&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;location&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;The city or destination, e.g. Paris or Tokyo&quot;,<br>                    }<br>                },<br>                &quot;required&quot;: [&quot;location&quot;],<br>                &quot;additionalProperties&quot;: False,<br>            },<br>            &quot;strict&quot;: True,<br>        }<br>    ]<br><br>    input_list = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: &quot;You are Safar, a travel planning AI agent&quot;,<br>        },<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: input(&quot;Ask you travel questions: &quot;),<br>        },<br>    ]<br><br>    response = client.responses.create(<br>        model=&quot;gpt-5.4-mini&quot;,<br>        input=input_list,<br>        tools=tools,<br>        tool_choice=&quot;required&quot;,<br>    )<br><br>    print(&quot;The model responded with:&quot;)<br>    print(response.output)<br><br>    input_list += response.output<br><br>    for item in response.output:<br>        if item.type != &quot;function_call&quot;:<br>            continue<br><br>        if item.name == &quot;get_weather&quot;:<br>            args = json.loads(item.arguments)<br>            print(f&quot;The model wants to call get_weather with: {args}&quot;)<br>            weather = get_weather(args[&quot;location&quot;])<br>            print(f&quot;The local Python function returned: {weather}&quot;)<br>            input_list.append({<br>                &quot;type&quot;: &quot;function_call_output&quot;,<br>                &quot;call_id&quot;: item.call_id,<br>                &quot;output&quot;: json.dumps(weather),<br>            })<br><br>    print(&quot;Sending the tool result back to the model&quot;)<br>    final_response = client.responses.create(<br>        model=&quot;gpt-5.4-mini&quot;,<br>        input=input_list,<br>        tools=tools,<br>    )<br><br>    print(&quot;Final answer:&quot;)<br>    print(f&quot;Model response: {final_response.output_text}&quot;)</pre><p>In the tools list, we have defined a function named get_weather according to <a href="https://developers.openai.com/api/docs/guides/function-calling">OpenAI function calling</a> guidelines and have specified the parameters that the model accepts using the parameters key. This definition follows <a href="https://json-schema.org/">JSON Schema specification.</a></p><p>Since, we add this tools list when making calls to OpenAI, the model will know that it has access to a weather tool and will be able to request a function call when needed.</p><p>In the script, you can see that when we receive a response from the model, we always check if the response type is a function call or not (item.type != &quot;function_call&quot;) and if the response is a request to call get_weather tool, we call the get_weather() Python function and send it back to the model:</p><pre>weather = get_weather(args[&quot;location&quot;])<br>input_list.append({<br>                &quot;type&quot;: &quot;function_call_output&quot;,<br>                &quot;call_id&quot;: item.call_id,<br>                &quot;output&quot;: json.dumps(weather),<br>            })</pre><p>Let’s run the script and ask the agent a question that would require a weather tool call:</p><pre>Ask you travel questions: Sunscreen needed in Goa?</pre><pre>The model responded with:<br>[ResponseFunctionToolCall(arguments=&#39;{&quot;location&quot;:&quot;Goa&quot;}&#39;, call_id=&#39;call_X9OBZhGwT3yhfmTAOclefWE8&#39;, name=&#39;get_weather&#39;, type=&#39;function_call&#39;, id=&#39;fc_05ba95ec38f46f7f006a17ce9e3bb0819a9a0b430001f7bd91&#39;, namespace=None, status=&#39;completed&#39;)]</pre><pre>The model wants to call get_weather with: {&#39;location&#39;: &#39;Goa&#39;}<br>The local Python function returned: {&#39;location&#39;: &#39;Goa&#39;, &#39;temperature&#39;: &#39;24 C&#39;, &#39;condition&#39;: &#39;Sunny&#39;, &#39;humidity&#39;: &#39;52%&#39;, &#39;wind&#39;: &#39;11 km/h&#39;}</pre><pre>Sending the tool result back to the model</pre><pre>Final answer:<br>Model response: Yes — sunscreen is a good idea in Goa. It’s sunny there right now, so UV exposure can be strong even if it feels pleasant.</pre><pre>Quick tips:<br>- Use broad-spectrum SPF 30+ (SPF 50 if you’ll be at the beach a lot)<br>- Reapply every 2 hours, and after swimming/sweating<br>- Don’t forget ears, neck, hands, and feet<br>- A hat and sunglasses help too</pre><pre>If you want, I can also suggest a Goa beach-day packing list.</pre><p>For our query, the model initially responds with a ResponseFunctionToolCall item. This requests our get_weather function to be called with location argument set as Goa.</p><p>Responding to this request, our script executes the function call and sends the function call response back to the model for getting the final response. The function call always returns temperature as 24 degree Celsius with condition as sunny. Trusting this data, the model produces its final response, suggesting the user to use a sunscreen.</p><p>The weather function defined in the above script is not a very useful one, it returns a hardcoded weather data for all requests. In a practical scenario, the function should make an actual call to a real Weather API to fetch data.</p><p>The above script illustrates the concept of an agent loop. Even though the example involves just one user request and model response, the agent takes intermediary steps (tool calls) before returning the final response.</p><p>Now let’s move to a real world example involving tools. We will provide web search capability to our agent by defining a custom SerpApi web search tool.</p><p>Providers usually have their own built-in tools for web search. However, <a href="https://serpapi.com/blog/build-an-ai-agent-with-claude-agent-sdk/#websearch-tool">these tools can be slow or unreliable</a> at times. To get live search data from search engines reliably, we can write a custom tool/function using <a href="https://pypi.org/project/serpapi/0.1.4/">SerpApi Python SDK</a>.</p><pre>import json<br>import os<br><br><br>def google_search(query):<br>    import serpapi<br><br>    client = serpapi.Client(api_key=os.environ[&quot;SERPAPI_KEY&quot;])<br><br>    results = client.search({<br>        &quot;engine&quot;: &quot;google&quot;,<br>        &quot;q&quot;: query,<br>    })<br><br>    return [<br>        {<br>            &quot;title&quot;: result.get(&quot;title&quot;),<br>            &quot;link&quot;: result.get(&quot;link&quot;),<br>            &quot;snippet&quot;: result.get(&quot;snippet&quot;),<br>        }<br>        for result in results.get(&quot;organic_results&quot;, [])[:5]<br>    ]<br><br><br>if __name__ == &#39;__main__&#39;:<br>    from openai import OpenAI<br><br>    client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>    tools = [<br>        {<br>            &quot;type&quot;: &quot;function&quot;,<br>            &quot;name&quot;: &quot;google_search&quot;,<br>            &quot;description&quot;: &quot;Search Google with SerpApi and return web search results.&quot;,<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;query&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;description&quot;: &quot;The Google search query to run&quot;,<br>                    }<br>                },<br>                &quot;required&quot;: [&quot;query&quot;],<br>                &quot;additionalProperties&quot;: False,<br>            },<br>            &quot;strict&quot;: True,<br>        }<br>    ]<br><br>    input_list = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: &quot;You are Safar, a travel planner. Use Google search when current destination information would improve your answer.&quot;,<br>        },<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: input(&quot;What travel question should I research? &quot;),<br>        },<br>    ]<br><br>    response = client.responses.create(<br>        model=&quot;gpt-5.4-mini&quot;,<br>        input=input_list,<br>        tools=tools,<br>        tool_choice=&quot;required&quot;,<br>    )<br><br>    print(&quot;The model responded with:&quot;)<br>    print(response.output)<br><br>    input_list += response.output<br><br>    for item in response.output:<br>        if item.type != &quot;function_call&quot;:<br>            continue<br><br>        if item.name == &quot;google_search&quot;:<br>            args = json.loads(item.arguments)<br>            print(f&quot;The model wants to call google_search with: {args}&quot;)<br><br>            search_results = google_search(args[&quot;query&quot;])<br>            print(f&quot;Step 7: SerpApi returned {len(search_results)} search results&quot;)<br><br>            input_list.append({<br>                &quot;type&quot;: &quot;function_call_output&quot;,<br>                &quot;call_id&quot;: item.call_id,<br>                &quot;output&quot;: json.dumps(search_results),<br>            })<br><br>    final_response = client.responses.create(<br>        model=&quot;gpt-5.4-mini&quot;,<br>        input=input_list,<br>        tools=tools,<br>    )<br><br>    print(f&quot;Model response: {final_response.output_text}&quot;)</pre><p>Here, we define a google_search() that accepts a query and performs a Google search with the query using SerpApi Python SDK. The function returns the first five search results obtained from Google.</p><p>Let’s see the results in action:</p><pre>The model responded with:<br>[ResponseFunctionToolCall(arguments=&#39;{&quot;query&quot;:&quot;La Tomatina 2026 date official&quot;}&#39;, call_id=&#39;call_mk2KL4xnvR0mexyt2lXFTHgE&#39;, name=&#39;google_search&#39;, type=&#39;function_call&#39;, id=&#39;fc_01af4c5fc07e8479006a192316ab20819bb10273439c89fb9a&#39;, namespace=None, status=&#39;completed&#39;)]</pre><pre>The model wants to call google_search with: {&#39;query&#39;: &#39;La Tomatina 2026 date official&#39;}<br>Step 7: SerpApi returned 5 search results</pre><pre>Model response: La Tomatina is happening on **Wednesday, August 26, 2026** in **Buñol, Spain**.</pre><pre>If you want, I can also help with:<br>- tickets<br>- how to get there from Valencia<br>- where to stay nearby</pre><p>This is the core idea behind tool calling. The model does not directly browse the web or fetch data by itself. Instead, it identifies when a tool is needed, asks for that tool to be called, and then uses the returned result to continue the conversation. This separation is useful because the model can focus on reasoning, while tools provide access to external systems and real-time information.</p><p>Without the google_search tool, the model would not be able to answer questions that require live data. It should respond with something like: “I don’t have access to real-time information.” By defining the tool, we give the model a safe and structured way to request the information it needs.</p><h3>MCP</h3><p>As you build more agents with more tools, a new problem emerges: every tool integration is custom-built and cannot easily be reused elsewhere. If you build a GitHub integration for one agent, you would have to rebuild it from scratch for another. That is where MCP comes in.</p><p><a href="https://serpapi.com/blog/model-context-protocol-mcp-a-unified-standard-for-ai-agents-and-tools/">Model Context Protocol (MCP)</a> is like USB-C for AI integrations. It is a standard protocol that lets models connect to external tools and data sources in a consistent, reusable way. Instead of building a custom integration for every tool, you write an MCP server once, and any model that supports MCP can use it.</p><p>Examples include:</p><ul><li><a href="https://github.com/github/github-mcp-server">GitHub MCP</a></li><li><a href="https://www.figma.com/mcp-catalog/">Figma MCP</a></li><li><a href="https://github.com/serpapi/serpapi-mcp">SerpApi MCP</a></li><li>database MCP servers</li><li>browser MCP servers</li><li>file system MCP servers</li></ul><p>With MCP, the model can discover supported functionality and call tools when needed. This makes integrations reusable across different models, clients, and applications. For a small agent, normal tool calling may be enough. For larger systems with many integrations, MCP can make the architecture cleaner.</p><p>Let’s see an example of MCP usage in practice. The script below uses the <a href="https://serpapi.com/blog/introducing-serpapis-mcp-server/">SerpApi MCP server</a> — using this, the agent will be able to call all the SerpApi supported engines like google, google_shopping, amazon, etc.</p><pre>import os<br><br>if __name__ == &#39;__main__&#39;:<br><br>    from openai import OpenAI<br><br>    client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>    serpapi_mcp_url = f&quot;https://mcp.serpapi.com/{os.environ[&#39;SERPAPI_KEY&#39;]}/mcp&quot;<br><br>    response = client.responses.create(<br>        model=&quot;gpt-5.4&quot;,<br>        tools=[<br>            {<br>                &quot;type&quot;: &quot;mcp&quot;,<br>                &quot;server_label&quot;: &quot;serpapi&quot;,<br>                &quot;server_description&quot;: &quot;SerpApi MCP server&quot;,<br>                &quot;server_url&quot;: serpapi_mcp_url,<br>                &quot;require_approval&quot;: &quot;never&quot;,<br>            }<br>        ],<br>        input=[<br>            {<br>                &quot;role&quot;: &quot;system&quot;,<br>                &quot;content&quot;: &quot;You are Cartwise, a shopping assistant. Help users compare products, prices, reviews, and buying options.&quot;,<br>            },<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: input(&quot;What do you want to shop for? &quot;),<br>            },<br>        ],<br>    )<br><br>    print(&quot;Full model response (includes MCP operations): &quot;)<br>    print(response.output)<br><br>    print(f&quot;Model response: {response.output_text}&quot;)</pre><p>SerpApi exposes the MCP server via the URL <a href="https://mcp.serpapi.com/">https://mcp.serpapi.com/</a>. Users can supply the API Key via the URL path as seen in the example: <a href="https://mcp.serpapi.com/%7Bos.environ[&#39;SERPAPI_KEY&#39;]}/mcp">https://mcp.serpapi.com/{os.environ[&#39;SERPAPI_KEY&#39;]}/mcp</a>.</p><p>The code here is relatively simpler compared to the tool calling example. We just need to provide the MCP server info via the tools argument:</p><pre>tools=[<br>            {<br>                &quot;type&quot;: &quot;mcp&quot;,<br>                &quot;server_label&quot;: &quot;serpapi&quot;,<br>                &quot;server_description&quot;: &quot;SerpApi MCP server&quot;,<br>                &quot;server_url&quot;: serpapi_mcp_url,<br>                &quot;require_approval&quot;: &quot;never&quot;,<br>            }<br>        ]</pre><p>From this definition alone, the model can discover supported MCP functionalities and it will be able to autonomously call the MCP server tools based on the user request.</p><p>Let’s ask the agent a shopping query. Here, I am asking it to find the price of a mobile device:</p><pre>What do you want to shop for? Find best price for Moto Razr Ultra phone</pre><pre>Full model response (includes MCP operations): <br>[ <br>  McpListTools(id=&#39;mcpl_06176a7178fb9f5c006a17f6c23578819ab2c977e7bc2b0bc7&#39;, server_label=&#39;serpapi&#39;, ...,</pre><pre>McpCall(id=&#39;mcp_06176a7178fb9f5c006a17f6c40930819aac6136e6a0f0ced8&#39;, arguments=&#39;{&quot;params&quot;:{&quot;q&quot;:&quot;Moto Razr Ultra phone price&quot;,&quot;engine&quot;:&quot;google_shopping&quot;,&quot;num&quot;:10},&quot;mode&quot;:&quot;compact&quot;}&#39;, name=&#39;search&#39;, server_label=&#39;serpapi&#39;, type=&#39;mcp_call&#39;, approval_request_id=None, error=None, output=&#39;{&quot;shopping_results&quot;: [{&quot;position&quot;: 1, &quot;title&quot;: &quot;Motorola Razr Ultra 2025&quot;, &quot;product_id&quot;: &quot;14521999409488109662&quot;, &quot;product_link&quot;: ...]}]}&#39;, status=&#39;completed&#39;), <br>  ResponseOutputMessage(id=&#39;msg_06176a7178fb9f5c006a17f6cc3e68819aa688012defa9cf78&#39;, content=[ResponseOutputText(annotations=[], text=&#39;Best price I found for a **new Moto Razr Ultra** is:...&#39;<br>]</pre><pre>Model response: Best price I found for a **new Moto Razr Ultra** is:</pre><pre>- **$699.99 at Best Buy** — Motorola Razr Ultra 2025  <br>  - was **$1,300**<br>  - rating: **4.0/5** from **520 reviews**<br>  - free delivery by Sat</pre><pre>Also matching:<br>- **$699.99 at Motorola US** — Motorola Razr 2025<br>- **$764.00 at Etoren** — Motorola Razr 50 Ultra<br>- **$1,049.99+** for some Razr 60 Ultra / 2026 variants</pre><p>The model response includes a series of operations:</p><ul><li><strong>McpListTools</strong>: This is the request from the model sent to the MCP server to list available operations. From this call, the model will know that SerpApi has a google_shopping engine for shopping searches.</li><li><strong>McpCall: </strong>Based on the above response, the model calls MCP server’s google_shopping engine with the query Moto Razr Ultra phone price. This call will fetch the shopping results via SerpApi MCP.</li><li><strong>ResponseOutputMessage</strong>: Once the above response is obtained, the model has enough information regarding the prices to formulate its response to the user. The model responds by listing the device price across a number of retailers.</li></ul><p>If we omitted the SerpApi MCP definition in the above script, the model should have responded with something like: “I cannot access real-time prices.” This is because the model itself does not have live data access unless we explicitly connect it to external tools or systems. MCP is one way to provide that connection in a standard way.</p><p>Now that we have seen how MCP connects agents to external capabilities, let’s look at another way to extend agent behavior: skills.</p><h3>Skills</h3><p>While tools handle actions, skills handle behavior. A <a href="https://agentskills.io/">skill</a> is a reusable set of instructions or a workflow that tells an agent how to perform a specific type of task well.</p><p>We have seen tools and MCP which are code-heavy. Tools are code that gets called by the model whereas MCP requires a server implementation according to the <a href="https://modelcontextprotocol.io/specification">Model Context Protocol spec</a>. Skills are relatively simple and can just be a plain text markdown file.</p><p>A skill can include:</p><ul><li>steps to follow</li><li>rules</li><li>examples</li><li>output formats</li><li>scripts</li><li>templates</li><li>best practices</li></ul><p>Skills are useful for repeated tasks. Examples include writing reports, analyzing PDFs, creating slides, debugging code, or handling customer support. Skills make agents more specialized.</p><p>Instead of putting every instruction into the system prompt, we can use skills where the model receives just the skill metadata in the context and will be able to load and use the full skill when the current task needs it.</p><p>A skill file is just a markdown file with the below format:</p><pre>---<br>name: skill-name<br>description: A description of what this skill does and when to use it.<br>---<br>Skill contents in markdown</pre><p>Let’s see a real-world example: The <a href="https://github.com/serpapi/skills">SerpApi Search Skill</a> provides instructions for the agent to interact with SerpApi realtime search APIs. You can see the <a href="https://github.com/serpapi/skills/blob/master/skills/serpapi-web-search/SKILL.md">skill.md file</a>, which provides instruction to the model to invoke various SerpApi API calls.</p><p>You can see a usage example below, where we use SerpApi skill to build a travel planning agent.</p><pre>import os<br>import subprocess<br>from pathlib import Path<br>from openai import OpenAI<br><br><br>MODEL = os.getenv(&quot;OPENAI_MODEL&quot;, &quot;gpt-5.4-mini&quot;)<br>SKILL_PATH = Path(__file__).resolve().parent / &quot;skills&quot; / &quot;serpapi-web-search&quot;<br><br>def run_shell_call(shell_call):<br>    print(f&quot;\nModel requested shell call: {shell_call.call_id}&quot;)<br>    print(f&quot;Commands: {shell_call.action.commands}&quot;)<br><br>    command_outputs = []<br><br>    for command in shell_call.action.commands:<br>        print(f&quot;\n[script] Running command: {command}&quot;)<br>        result = subprocess.run(<br>            command,<br>            shell=True,<br>            executable=&quot;/bin/zsh&quot;,<br>            capture_output=True,<br>            text=True,<br>            check=False,<br>        )<br><br>        print(f&quot;[script] Exit code: {result.returncode}&quot;)<br>        if result.stdout:<br>            print(f&quot;[script] stdout:\n{result.stdout[:1500]}&quot;)<br>        if result.stderr:<br>            print(f&quot;[script] stderr:\n{result.stderr[:1500]}&quot;)<br><br>        command_outputs.append({<br>            &quot;stdout&quot;: result.stdout,<br>            &quot;stderr&quot;: result.stderr,<br>            &quot;outcome&quot;: {<br>                &quot;type&quot;: &quot;exit&quot;,<br>                &quot;exit_code&quot;: result.returncode,<br>            },<br>        })<br><br>    output_item = {<br>        &quot;type&quot;: &quot;shell_call_output&quot;,<br>        &quot;call_id&quot;: shell_call.call_id,<br>        &quot;output&quot;: command_outputs,<br>    }<br><br>    if shell_call.action.max_output_length is not None:<br>        output_item[&quot;max_output_length&quot;] = shell_call.action.max_output_length<br><br>    return output_item<br><br>if __name__ == &quot;__main__&quot;:<br>    client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br>    input_list = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: &quot;You are Safar, a travel planning assistant.&quot;,<br>        }<br>    ]<br><br>    tools = [<br>        {<br>            &quot;type&quot;: &quot;shell&quot;,<br>            &quot;environment&quot;: {<br>                &quot;type&quot;: &quot;local&quot;,<br>                &quot;skills&quot;: [<br>                    {<br>                        &quot;name&quot;: &quot;serpapi-web-search&quot;,<br>                        &quot;description&quot;: &quot;Search current travel information with the SerpApi CLI.&quot;,<br>                        &quot;path&quot;: str(SKILL_PATH),<br>                    }<br>                ],<br>            },<br>        }<br>    ]<br><br>    print(&quot;Type &#39;exit&#39; or &#39;quit&#39; to stop.\n&quot;)<br><br>    waiting_for_user = True<br><br>    while True:<br><br>        if waiting_for_user:<br>            user_query = input(&quot;You: &quot;)<br><br>            if user_query.lower() in [&quot;exit&quot;, &quot;quit&quot;]:<br>                break<br><br>            input_list.append({<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: user_query,<br>            })<br>            waiting_for_user = False<br><br>        print(&quot;\n[script] Sending request to the model.&quot;)<br>        response = client.responses.create(<br>            model=MODEL,<br>            input=input_list,<br>            tools=tools,<br>        )<br><br>        input_list += response.output<br><br>        shell_calls = [item for item in response.output if item.type == &quot;shell_call&quot;]<br>        print(f&quot;[script] Shell calls requested: {len(shell_calls)}&quot;)<br><br>        if not shell_calls:<br>            print(f&quot;Model response: {response.output_text}\n&quot;)<br>            waiting_for_user = True<br>            continue<br><br>        for shell_call in shell_calls:<br>            input_list.append(run_shell_call(shell_call))<br><br>        print(&quot;\n[script] Sending shell output back to the model.&quot;)<br></pre><p>The script uses local skills capability of OpenAI SDK — we have the skill files added in skills/serpapi-web-search folder relative to the scripts parent directory.</p><p>Skills can be specified using the below format:</p><pre>tools = [<br>        {<br>            &quot;type&quot;: &quot;shell&quot;,<br>            &quot;environment&quot;: {<br>                &quot;type&quot;: &quot;local&quot;,<br>                &quot;skills&quot;: [<br>                    {<br>                        &quot;name&quot;: &quot;serpapi-web-search&quot;,<br>                        &quot;description&quot;: &quot;Search current travel information with the SerpApi CLI.&quot;,<br>                        &quot;path&quot;: str(SKILL_PATH),<br>                    }<br>                ],<br>            },<br>        }<br>    ]</pre><p>We provide the skill name, description and path to the agent. When using skills, OpenAI SDK will emit shell calls that must be run in the terminal. This is needed so that the agent can list and view the full skill file contents that are present locally. We have a run_shell_call() function defined for this. Whenever the model requests for a shell call, we will run this function and pass back the shell results to the model.</p><blockquote>Since this example lets the model request shell commands, only run it in a trusted, sandboxed environment. Do not give shell access to untrusted prompts, repositories, or skill files without review.</blockquote><p>Now let’s run the agent and ask it a travel planning question. We will ask the model about hotel prices in Goa, India:</p><pre>Type &#39;exit&#39; or &#39;quit&#39; to stop.<br>You: Find Goa hotel prices for a vacation: two nights from 10 June 26</pre><pre>[script] Sending request to the model.<br>[script] Shell calls requested: 1</pre><pre>Model requested shell call: call_Cgs0D4tNOZFPZ30GNVJzJNHZ<br>Commands: [&#39;cd .../skills/serpapi-web-search &amp;&amp; cat SKILL.md&#39;]</pre><pre>[script] Running command: cd .../skills/serpapi-web-search &amp;&amp; cat SKILL.md<br>[script] Exit code: 0<br>[script] stdout:<br>---<br>name: serpapi-web-search<br>description: &gt;-<br>  Search the web using SerpApi&#39;s 100+ search engines. Use this skill whenever<br>  the user needs current or web-sourced information: ...</pre><pre>[script] Sending shell output back to the model.</pre><pre>[script] Sending request to the model.<br>[script] Shell calls requested: 1</pre><pre>Model requested shell call: call_Y2PGcBkpSEkzIikqu1H30uRW<br>Commands: [&quot;cd .../skills/serpapi-web-search &amp;&amp; sed -n &#39;1,220p&#39; rules/ENGINES.md&quot;]</pre><pre>[script] Running command: cd .../skills/serpapi-web-search &amp;&amp; sed -n &#39;1,220p&#39; rules/ENGINES.md<br>[script] Exit code: 0<br>[script] stdout:<br># SerpApi Search Engines Catalog</pre><pre>Complete list of 107 SerpApi search engines. Use the `engine` parameter to select the desired search engine.<br>...</pre><pre>[script] Sending shell output back to the model.</pre><pre>[script] Sending request to the model.<br>[script] Shell calls requested: 1</pre><pre>Model requested shell call: call_oncTqSWJWQoDbqJS06aJP1OD<br>Commands: [&#39;cd .../skills/serpapi-web-search &amp;&amp; serpapi search engine=google_hotels q=&quot;Goa&quot; check_in_date=2026-06-10 check_out_date=2026-06-12 --fields \&#39;properties[0:20]\&#39;&#39;]</pre><pre>[script] Running command: cd .../skills/serpapi-web-search &amp;&amp; serpapi search engine=google_hotels q=&quot;Goa&quot; check_in_date=2026-06-10 check_out_date=2026-06-12 --fields &#39;properties[0:20]&#39;<br>[script] Exit code: 0<br>[script] stdout:<br>{<br>  &quot;properties&quot;: [<br>    {<br>      &quot;type&quot;: &quot;hotel&quot;,<br>      &quot;name&quot;: &quot;Vivanta Goa, Miramar&quot;,<br>      &quot;description&quot;: &quot;Swanky hotel across from the beach featuring a rooftop pool, a stylish restaurant &amp; a 24-hour gym.&quot;,<br>      ...<br></pre><pre>[script] Sending shell output back to the model.</pre><pre>[script] Sending request to the model.<br>[script] Shell calls requested: 0</pre><pre>Model response: I found live Goa hotel prices for **2 nights: 10 Jun 2026 to 12 Jun 2026**.</pre><pre>Sample prices from Google Hotels:<br>- **Vivanta Goa, Miramar** — **$82/night**, **$164 total**<br>- **Aloha Holiday Resort** — **$17/night**, **$33 total**<br>- Other properties in the Goa search were showing a wide range, from budget stays to luxury resorts.</pre><pre>A few notes:<br>- These are **current live rates** and can change quickly.<br>- The prices shown are from hotel search results and may be **before taxes/fees**.<br>- I searched broadly for **Goa**; if you want, I can narrow it down by:<br>  - **North Goa / South Goa**<br>  - **Budget / mid-range / luxury**<br>  - **Beachfront**<br>  - **2 adults vs family**</pre><pre>If you want, I can make a short list of the **best 10 Goa hotels under a budget you choose**.</pre><p>As seen from the output, the model initially requested a shell call that runs cat SKILL.md which is to read the skill contents.</p><p>With the skill contents obtained, the model proceeds with another shell call sed -n &#39;1,220p&#39; rules/ENGINES.md which lists all SerpApi supported engines. With this data, the model will be able to get all supported SerpApi search engines and choose the best one for the task.</p><p>Next, model requests running the command serpapi search engine=google_hotels q=&quot;Goa&quot; check_in_date=2026-06-10 check_out_date=2026-06-12 --fields &#39;properties[0:20]&#39; which uses <a href="https://github.com/serpapi/serpapi-cli">SerpApi CLI</a> to get results from Google Hotels. We run this shell command on our end and pass the results to the model that includes JSON results from Google Hotels API.</p><p>With this data obtained, the model was able to generate its final response and give us suggestions for Hotels to book in Goa along with the prices.</p><p>Now that we have seen prompts, memory, tools, MCP, and skills, we can put these pieces into one simple stack.</p><h3>Agent Capability Stack</h3><p>An agent can be understood as a stack of capabilities. We have seen the core building blocks of an agent: system prompts, tools, MCP, and skills. Now, let’s compare how they fit together in the agent capability stack.</p><p>At the bottom, we have the system prompt. This defines global behavior and constraints.</p><p>Then we have skills. Skills provide packaged procedures for specific task types.</p><p>Then we have tools. Tools let the agent do things in the world.</p><p>Then we have MCP. MCP gives us a standard way to connect models to tools, files, APIs, databases, IDEs, browsers, and other systems.</p><p>We can think about the stack like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtDQcPzV5hVSPoKALL649A.png" /></figure><p>Use a system prompt for safety boundaries, tone, refusal style, and stable rules.</p><p>Use a skill when you want the model to follow a repeatable workflow or use scripts and templates.</p><p>Use tools when the model must call external services, fetch live state, create side effects, or interact with the environment.</p><p>Use MCP when you want to expose tools and resources through a standard protocol.</p><h3>Summary and Next Steps</h3><p>In this tutorial, we started out with the components of an AI agent and built a few simple agents for use cases such as shopping and travel. We provided capabilities to agents using tool calling, MCP, and Skill files.</p><p>To explore on your own, you can find the code snippets used in the tutorial in this <a href="https://github.com/serpapi/tutorials/tree/master/python_projects/ai_agents_in_python">GitHub repo</a>.</p><p>If you are looking for a different SDK or tool to start with, like the Claude agent SDK or n8n, we have you covered:</p><ul><li><a href="https://serpapi.com/blog/build-an-ai-agent-with-claude-agent-sdk/">Build an AI Agent with the Claude Agent SDK (Tutorial 2026)</a></li><li><a href="https://serpapi.com/blog/how-to-build-an-ai-agent-with-n8n-and-live-google-search-data/">How to Build an AI Agent with n8n and Live Google Search Data</a></li></ul><p>Even though we covered the basics for building simple agents, some important next steps to learn more about are:</p><ul><li>multi-agent systems</li><li>observability</li><li>error handling</li><li>permissions</li><li>context compaction</li><li>evaluation</li></ul><p>A multi-agent system has multiple agents, where each agent can be specialized for a specific goal. These agents can communicate with each other. We can also have verifier models that check the output from other models.</p><p>Similar to building a backend application, we need <strong>observability</strong> and error handling for agents. The model can hallucinate, choose the wrong tool, pass bad arguments, or get stuck in a loop. We need a way to monitor this behavior and improve the system over time.</p><p><strong>Permissions</strong> are also important. An agent that can read files is useful. An agent that can delete files or send emails should be more carefully controlled. We should decide which actions require user approval.</p><p><strong>Context compaction</strong> is another important idea. As the conversation grows, the agent cannot keep everything forever. It needs to summarize old information and keep only what is useful for the next step.</p><p><strong>Evaluation</strong> helps us understand whether the agent is actually doing a good job. We can test the agent on sample tasks, check if it used the right tools, verify whether the final answer is correct, and compare outputs across different prompts or models. Without evaluation, it is hard to know if the agent is improving or just producing confident-looking answers.</p><p>The best way to understand agents is to build small ones, give them real tasks, inspect their tool calls, and evaluate their outputs. Start with a simple loop, add tools carefully, introduce memory only when needed, and add observability before trusting the agent with important actions. And if your agent needs real-time data access, you can explore <a href="https://serpapi.com/search-engine-apis">SerpApi APIs</a> to extend its capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f70fdf6dfb18" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-an-ai-agent-in-python-f70fdf6dfb18">Building an AI Agent in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye GIL — Exploring Free Threaded Python 3.14]]></title>
            <link>https://medium.com/@adarshd/goodbye-gil-exploring-free-threaded-python-3-14-44ce16218d64?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/44ce16218d64</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[global-interpreter-lock]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 18:23:14 GMT</pubDate>
            <atom:updated>2025-10-22T18:23:14.730Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goodbye GIL — Exploring Free Threaded Python 3.14</h3><p>I compared execution time of code — which included CPU &amp; I/O bound scripts and a WSGI app using the default and free-threaded Python 3.14 interpreters. This was for my talk: “Goodbye GIL — Exploring Free Threaded Mode in Python” at <a href="https://2025.pycon.jp/ja/timetable/talk/KLCT8T">PyCon JP 2025</a>.</p><p>The talk involved a demo running CPU &amp; I/O bound workloads (standalone script and flask endpoints) with GIL enabled and disabled, and comparing the performance.</p><blockquote><em>The benchmarking was done using Python 3.14 RC2 (the talk was before Python 3.14 released).</em></blockquote><p>I originally presented this at PyCascades 2025, using Python 3.13. This time, I updated the benchmarks to Python 3.14 RC2, and added few updates regarding free threaded mode. This post is a recreation of the talk content in text format.</p><blockquote><a href="https://speakerdeck.com/adarshd/goodbye-gil-exploring-the-free-threaded-mode-in-python"><em>Access Presentation Slides Here</em></a><em> · </em><a href="https://github.com/adarshdigievo/pycon_jp_goodbye_gil_talk"><em>Benchmarking Scripts</em></a></blockquote><h3>GIL</h3><p><a href="https://realpython.com/python-gil/">GIL (Global Interpreter Lock)</a> is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once.</p><p>GIL simplified CPython’s internals such as memory management. This is because code can be written with the assumption that at any single point in time, only one thread will be executing Python bytecode.</p><h3>The Problem: Impact on Multithreading</h3><p>The GIL can be a bottleneck in CPU-bound and multithreaded code. In CPU-bound multithreaded programs, threads often compete for the GIL, leading to context switching and reduced performance. I/O bounded programs are less affected, as threads can release the GIL during I/O operations.</p><p>Historically, multiprocessing was the primary way to achieve parallelism in Python for CPU-bound tasks, but with inter-process communication overhead.</p><h3>PEP 703: Making the GIL Optional in CPython</h3><p>PEP 703 proposed making the Global Interpreter Lock optional in CPython. It introduces “free-threaded build” of Python where the GIL is disabled. The PEP aims to unlock true parallel execution for Python threads, especially for CPU-bound workloads.</p><p>It was experimental in Python 3.13, eventually evolving into an optional (or possibly default-disabled) feature in future releases.</p><h3>Challenges of Free-Threaded Python</h3><ul><li>Backward Compatibility: Many C extensions are written assuming the GIL will exist. These extensions may not be thread-safe without the GIL, leading to potential crashes or data corruption.</li><li>Performance Overhead: Free-threaded builds may run single-threaded code slower. This is due to the need for additional locking mechanisms to ensure thread safety (since multiple threads will be executing at a single point in time).</li></ul><h3>PEP 779 — Criteria for supported status for free-threaded Python:</h3><p>The PEP outlines criteria for when free-threaded Python can be considered a supported feature. This included requirements that the free threaded build needs to meet across performance, stability, etc.</p><p>PEP 779 evaluated the free-threaded build against these criteria in Python 3.13 and the criteria were satisfied.</p><blockquote><em>“The free-threaded build of Python is now supported and no longer experimental. This is the start of phase II where free-threaded Python is officially supported but still optional.” — Python 3.14 Release Notes</em></blockquote><p>The performance penalty on single-threaded code in free-threaded mode is now roughly 5–10%.</p><h3>Setting Up Free Threaded Python</h3><p>The official guide to set-up free-threaded Python is available <a href="https://py-free-threading.github.io/installing_cpython">here</a>.</p><p>Windows/macOS users can use the installers from Python.org that include free-threaded builds.</p><p>For Ubuntu, free-threaded Python 3.14 can be installed from the deadsnakes PPA:</p><pre>sudo add-apt-repository ppa:deadsnakes<br>sudo apt-get update<br>sudo apt-get install python3.14-nogil</pre><h3>Benchmarks</h3><p>This section presents benchmarks comparing performance of standard Python 3.14 (with GIL) and free-threaded Python 3.14 (without GIL).</p><p>For benchmarking, I created two virtual environments:</p><ul><li>One with standard Python 3.14 (with GIL)</li><li>Another with free-threaded Python 3.14 (3.14t, without GIL, python3.14t -m venv .venv)</li></ul><p>Different workloads were benchmarked. When running the benchmarks, the GIL status was checked to ensure the correct interpreter was used.</p><ul><li>GIL status can be checked using any of the following methods:</li></ul><pre>import sys<br><br>print(sys._is_gil_enabled())  # True if GIL is enabled, False otherwise</pre><p>OR:</p><pre>import sysconfig<br><br>sysconfig.get_config_var(”Py_GIL_DISABLED”)  # True if GIL is disabled, False otherwise</pre><p><strong>View `check_gil.py` code</strong></p><pre>import sys<br>import sysconfig<br><br><br>def show_gil_status():<br>  gil_status = sys._is_gil_enabled()<br><br>  print(F”{sys._is_gil_enabled()=}”)<br><br>  if gil_status:<br>    print(”\nRunning in default interpreter - GIL is enabled\n”)<br>  else:<br>    print(”\nRunning in Free threaded interpreter - GIL is disabled\n”)<br><br><br>def check_free_threading_support():<br>  print(f”\n{sysconfig.get_config_vars().get(’Py_GIL_DISABLED’)=}\n”)<br><br><br>if __name__ == ‘__main__’:<br>  check_free_threading_support()<br><br>  show_gil_status()</pre><h3>First benchmark — Single Threaded Program</h3><p>The first benchmark involves running a single threaded program that sums numbers from 1 to 1 million, repeated 100 times and timed using timeit module.</p><p><strong>Benchmarking code</strong></p><pre><br>import timeit<br><br>from check_gil import show_gil_status<br><br><br>def single_threaded_benchmark():<br>  show_gil_status()<br><br>  # Sum of numbers from 1 to 1 million<br>  code_to_test = “”“<br><br>total = 0<br>for i in range(1_000_000):<br>    total += i<br><br>“”“<br><br>  # Use timeit to measure execution time - Run the code 100 times<br>  execution_time = timeit.timeit(code_to_test, number=100)<br><br>  print(f”Execution time: {execution_time:.6f} seconds”)<br><br><br>if __name__ == ‘__main__’:<br>  single_threaded_benchmark()</pre><blockquote><em>Benchmark Results: In my system, the free threaded execution was ~15% slower than default interpreter. Default interpreter completed in ~3s, while free-threaded took ~3.5s.</em></blockquote><p>Execution time of individual runs are added in the next section, in the Observations table.</p><h3>I/O Bound Program</h3><p>Next, let’s benchmark an I/O bound program that performs file write and read operations.</p><p>We execute the code in single threaded mode as well as multi-threaded mode using ThreadPoolExecutor and repeat both with GIL enabled and disabled.</p><p>The code creates a temporary file, writes data to it in chunks, forces flush and fsync to ensure data is committed to disk, then reads the data back in chunks. This simulates a realistic I/O workload.</p><p><strong>Benchmarking code</strong></p><pre>import os<br>import tempfile<br>import time<br>from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED<br><br>from check_gil import show_gil_status<br><br>FILE_MB = 24  # total temp file size per op<br><br>CHUNK_KB = 64  # write/read granularity<br><br>SINGLE_OPS = 8  # Single threaded executions<br><br>MULTI_OPS = 12  # Multi-threaded executions<br>THREADS = 6<br><br># ===== Derived =====<br>_CHUNK_BYTES = CHUNK_KB * 1024<br>_TOTAL_CHUNKS = (FILE_MB * 1024 * 1024) // _CHUNK_BYTES<br>BUF = b”A” * _CHUNK_BYTES<br><br><br>def _write_pass(f, buf):<br>  “”“Write the buffer repeatedly across the file, forcing flush+fsync each time to ensure data is committed to disk.”“”<br>  f.seek(0)<br><br>  # make sure each write is flushed and synced to disk - to increase IO load.<br>  for _ in range(_TOTAL_CHUNKS):<br>    f.write(buf)<br>    f.flush()<br>    os.fsync(f.fileno())<br><br><br>def _read_pass(f):<br>  “”“Read the entire file back chunk by chunk to simulate sequential disk read workload.”“”<br>  f.seek(0)<br>  remaining = _TOTAL_CHUNKS<br>  while remaining &gt; 0:<br>    data = f.read(_CHUNK_BYTES)<br>    if not data:<br>      break<br>    remaining -= 1<br><br><br>def io_bound():<br>  “”“Perform one full write+read cycle on a temporary file with forced disk syncs, then clean up the file.”“”<br>  tmp = tempfile.NamedTemporaryFile(prefix=”io_bench_”, delete=False)<br>  tmp_name = tmp.name<br>  tmp.close()<br>  try:<br>    with open(tmp_name, “wb”, buffering=0) as f0:<br>      f0.truncate(FILE_MB * 1024 * 1024)<br><br>    flags = os.O_RDWR | os.O_CREAT<br><br>    fd = os.open(tmp_name, flags, 0o600)<br>    f = os.fdopen(fd, “r+b”, buffering=0)<br><br>    try:<br>      _write_pass(f, BUF)<br>      _read_pass(f)<br>    finally:<br>      f.close()<br><br>  finally:<br>    try:<br>      os.remove(tmp_name)<br>    except Exception:<br>      pass<br>  return “IO task done!”<br><br><br>def single_threaded():<br>  for _ in range(SINGLE_OPS):<br>    io_bound()<br><br><br>def multi_threaded():<br>  with ThreadPoolExecutor(max_workers=THREADS) as executor:<br>    futs = [executor.submit(io_bound) for _ in range(MULTI_OPS)]<br>    wait(futs, return_when=ALL_COMPLETED)<br><br><br>def run_benchmark():<br>  t0 = time.time()<br>  single_threaded()<br>  print(f”Single thread Exec Time: {time.time() - t0:.2f}s”)<br><br>  t1 = time.time()<br>  multi_threaded()<br>  print(f”Multi thread Exec Time: {time.time() - t1:.2f}s”)<br><br><br>if __name__ == ‘__main__’:<br>  show_gil_status()<br>  print(f”[Config] FILE_MB={FILE_MB}, CHUNK_KB={CHUNK_KB} “<br>        f”SINGLE_OPS={SINGLE_OPS}, MULTI_OPS={MULTI_OPS}, THREADS={THREADS}”)<br>  run_benchmark()</pre><blockquote><em>Benchmark Results: In case of this I/O bound operation, both interpreters performed comparably. Single threaded execution took ~2.9s in both interpreters. Multi-threaded execution took ~2.4s in both interpreters.</em></blockquote><h3>CPU Bound Program</h3><p>The task involves performing a computationally intensive operation. We calculate primes upto the upper limit of 2 million.</p><p>The task is done using two modes:</p><ol><li>Single-threaded mode: The prime counting function is executed in a single thread.</li><li>Multi-threaded mode: The prime counting function is divided into chunks, and each chunk is processed in a separate thread using ThreadPoolExecutor. This way, we can see the multi-threading related performance changes.</li></ol><p><strong>View benchmarking code</strong></p><pre>import math<br>import time<br>import os<br>from concurrent.futures import ThreadPoolExecutor, as_completed<br><br># CPU bound task: count primes up to UPPER<br><br># Upper limit for prime search - 2 Million<br>UPPER = 2_000_000<br><br># Chunk size for multithreading<br>CHUNK_SIZE = 50_000<br><br><br>def is_prime(n: int) -&gt; bool:<br>  if n &lt; 2:<br>    return False<br>  if n % 2 == 0:<br>    return n == 2<br>  r = int(math.isqrt(n))<br><br>  # check if number is divisible by any odd number up to sqrt(n)<br>  for f in range(3, r + 1, 2):<br>    if n % f == 0:<br>      return False<br>  return True<br><br><br>def count_primes_range(a: int, b: int) -&gt; int:<br>  # Count primes in [a, b)<br>  cnt = 0<br>  # handle 2 explicitly, then iterate odds<br>  if a &lt;= 2 &lt; b:<br>    cnt += 1<br>  start = max(a, 3)<br>  if start % 2 == 0:<br>    start += 1<br>  for n in range(start, b, 2):<br>    if is_prime(n):<br>      cnt += 1<br>  return cnt<br><br><br># Calculate primes in single-threaded mode - 3 - 2 Million in a single thread<br>def single_threaded(upper: int) -&gt; tuple[int, float]:<br>  t0 = time.perf_counter()<br>  cnt = count_primes_range(2, upper)<br>  dt = time.perf_counter() - t0<br>  return cnt, dt<br><br><br># Calculate primes in multi-threaded mode using threads. Each thread processes a chunk of 50,000 (CHUNK_SIZE).<br>def multithreaded_threads(upper: int, max_workers: int | None = None) -&gt; tuple[int, float, int]:<br>  # Split [2, upper) into chunks and process with threads.<br><br>  if max_workers is None:<br>    max_workers = max(2, os.cpu_count() or 4)<br><br>  # Build chunks<br>  chunks = []<br>  lo = 2<br>  while lo &lt; upper:<br>    hi = min(lo + CHUNK_SIZE, upper)<br>    chunks.append((lo, hi))<br>    lo = hi<br><br>  t0 = time.perf_counter()<br>  total = 0<br>  with ThreadPoolExecutor(max_workers=max_workers) as ex:<br>    futures = [ex.submit(count_primes_range, a, b) for a, b in chunks]<br>    for fut in as_completed(futures):<br>      total += fut.result()<br>  dt = time.perf_counter() - t0<br>  return total, dt, max_workers<br><br><br>def main():<br>  print(f”Computing prime count in [2, {UPPER})”)<br>  cnt1, t1 = single_threaded(UPPER)<br>  print(f”[Single-threaded] primes={cnt1:,}  time={t1:.2f}s”)<br><br>  cnt2, t2, k = multithreaded_threads(UPPER)<br>  print(f”[Multithreaded (threads={k})] primes={cnt2:,}  time={t2:.2f}s”)<br><br>  # Sanity check: both modes should count the same<br>  print(”Results equal:”, cnt1 == cnt2)<br><br><br>if __name__ == “__main__”:<br>  main()</pre><blockquote><em>Benchmark Results: In single threaded mode, default interpreter completed in ~2.7s, while free-threaded took ~3.1s. For multi-threaded execution, default interpreter took ~2.7s, while free-threaded completed in ~0.8s — a significant improvement.</em></blockquote><p>When using free-threaded Python, we got performance penalty in single-threaded code, but significant performance in multi-threaded mode.</p><h3>WSGI App with Flask</h3><p>Flask app is run in development mode with Flask’s built-in server (multi-threaded by default). So the WSGI server can be thought of as a multi-threaded server.</p><p>We have two API Endpoints defined — 1 running I/O bound operation &amp; other running CPU bound task.</p><p>We benchmark the endpoints using load testing tool <a href="https://k6.io/">k6</a>. k6 creates multiple virtual users (VUs) simulating real-users of the application and makes requests to the endpoints.</p><p><strong>View Flask `app.py`</strong></p><pre><br>import threading<br><br>from flask import Flask<br><br>import tempfile<br>import os<br><br>from check_gil import show_gil_status<br><br>app = Flask(__name__)<br><br><br># CPU-bound task<br>def heavy_computation():<br>  # sum of squares from 0 to 10 million<br>  return sum(i * i for i in range(10 ** 7))<br><br><br># Routes<br>@app.route(’/’)<br>def root():<br>  return f”{threading.active_count()=}”<br><br><br># Routes<br>@app.route(’/cpu’)<br>def cpu_bound():<br>  print(threading.active_count())<br>  heavy_computation()<br>  return “CPU task done!”<br><br><br>@app.route(’/io’)<br>def io_bound():<br>  print(threading.active_count())<br><br>  with tempfile.TemporaryFile() as f:<br>    f.write(b”Hello, World!” * 10000000)<br>    f.seek(0)<br>    f.read()<br>    os.remove(f.name)  # Added for more IO work<br><br>  with tempfile.TemporaryFile() as f:<br>    f.write(b”Hello, World!” * 10000000)<br>    f.seek(0)<br>    f.read()<br>    os.remove(f.name)  # Added for more IO work<br><br>  with tempfile.TemporaryFile() as f:<br>    f.write(b”Hello, World!” * 10000000)<br>    f.seek(0)<br>    f.read()<br>    os.remove(f.name)  # Added for more IO work<br><br>  return “IO task done!”<br><br><br>if __name__ == ‘__main__’:<br>  show_gil_status()<br><br>  # By default, Flask’s built-in server is multi-threaded.<br>  # This can be verified by visiting the root endpoint (/).<br>  app.run()</pre><p>Benchmarks were done using the k6. The benchmark scripts used are available <a href="https://github.com/adarshdigievo/pycon_jp_goodbye_gil_talk/tree/master/flask_app/benchmark">here</a></p><p>I configured k6 to run for 20 seconds with 15 virtual users (VUs) making requests to the Flask app endpoints. The benchmark was done using k6 run benchmark_io.js and k6 run benchmark_cpu.js commands.</p><blockquote><em>Results: For I/O bound endpoint, both interpreters performed comparably — ~31–32 requests completed in 20 seconds. For CPU bound endpoint, free-threaded Python showed significant improvement — ~91 requests completed in 20 seconds, compared to ~47 requests with GIL enabled.</em></blockquote><p>The results indicate that in our WSGI app, free-threaded Python can handle CPU-bound endpoints more efficiently in a multi-threaded environment, while I/O-bound workloads remain largely unaffected by the presence or absence of the GIL.</p><h3>Observations</h3><p>The below table shows the consolidated benchmark results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*_Q-MubxAPrfkF7AS.png" /></figure><p>For flask app, the benchmark lists the number of requests completed in 20 seconds (higher the better).</p><p>Summary of benchmarks:</p><ul><li>Single threaded — Worse performance in free-threaded mode.</li><li>I/O Bound programs — Minimal/no impact. Both interpreters perform comparably.</li><li>For <strong>CPU Bound, Multi-threaded</strong> Programs, free-threaded Python shows significant performance improvements.</li></ul><h3>The future of Free Threaded Python</h3><ol><li>In 2024, CPython 3.13 was released with support for a — disable-gil build time flag. There are two ABIs for CPython, one with the GIL and one without. Extension authors target both ABIs.</li><li>We are here now (PEP 779 Acceptance): “The free-threaded build of Python is now supported and no longer experimental”.</li><li>After 2–3 releases, (i.e., in 2026–2027), CPython is released with the GIL controlled by a runtime environment variable or flag. The GIL is enabled by default. There is only a single ABI.</li><li>After another 2–3 release (i.e., 2028–2030), CPython switches to the GIL being disabled by default. The GIL can still be enabled at runtime via an environment variable or command line flag.</li></ol><h3>Migration Checklist</h3><p><strong>Free-threaded Python:</strong></p><ul><li>Great for CPU bound Tasks + Threading</li><li>Great for scenarios where parallelisation is needed — but multiprocessing is too complex / not suitable</li></ul><p><strong>Precautions</strong>:</p><ul><li>Always benchmark using your own workload before making a switch.</li><li>Watch out for library compatibility issues/bugs. Proper testing is needed before production adoption with your workloads.</li></ul><h3>Conclusion</h3><ul><li>Free-threaded Python in 3.14 shows significant performance improvements for CPU-bound multithreaded workloads, while maintaining comparable performance for I/O-bound tasks. A new concurrency mode is unlocked for CPU bound programs without overhead of inter-process communication</li><li>Single-threaded performance sees a slight decrease in performance. The default interpreter works best for single-threaded programs. The performance penalty will be reduced further in future releases.</li><li>Performance is comparable for I/O-bound workloads in both modes.</li></ul><p>PS: I published my book “Deep Dive Python” last month. <a href="https://deepdivepython.com/">Get the book</a> to learn Python concepts straight from real open-source code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44ce16218d64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Will AI Replace Junior Developers? I Asked Experts at Pycon US]]></title>
            <link>https://python.plainenglish.io/will-ai-replace-junior-developers-i-asked-experts-at-pycon-us-c110748ccc22?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/c110748ccc22</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pycon]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 14:59:14 GMT</pubDate>
            <atom:updated>2025-06-22T14:47:04.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*srSdHEXIBL88C95O" /></figure><p>I attended <em>Pycon US in Pittsburgh</em> — This was my first in-person Pycon US.</p><p>At this PyCon, I decided to try something different. I skipped most of the talks and focused on the hallway track — just walking around, meeting people, and asking questions.</p><p>I was also presenting a poster at PyCon — on using Python to improve at chess: <a href="https://www.linkedin.com/redir/redirect?url=https%3A%2F%2Fgithub%2Ecom%2Fadarshdigievo%2Ftalks%2Ftree%2Fmain%2FPycon%2520US%252025%2520-%2520Improving%2520in%2520Chess&amp;urlhash=UEDf&amp;trk=article-ssr-frontend-pulse_little-text-block">presentation materials here.</a></p><p>Before the conference, I had prepared a few questions I wanted to ask the Python people:</p><ul><li>What do you think is the future of programming?</li><li>Will AI take over programming jobs in the next 2–3 years?</li><li>What AI tools do you use in your daily work?</li><li>What advice do you have for Python developers?</li></ul><p>Most of the people I talked to are familiar names in the Python community. I’ve read their blog posts, watched their talks, or used their open-source tools. There were many more people I wish I had a chance to talk to, but I’m glad I got to speak with the ones I did.</p><p>One thing surprised me — very few people said AI will replace developers. I expected more.</p><p>Later I realized why. Most of the folks I spoke to are working on deep, core programming problems — like optimizing CPython, or building dev tools. These are areas where current AI tools aren’t that useful. LLMs haven’t seen much of that code. So maybe it’s not that surprising after all.</p><p>Here’s what they said:</p><h3><strong>Guido van Rossum — Dutch programmer</strong></h3><p>Guido said AI won’t replace programmers.</p><p>He’s not a fan of “vibe coding” (letting AI write code you don’t understand). He is not impressed with the quality of the code generated by current tools. But he does use GitHub Copilot (for autocomplete) and he expects AI assistants to get much better in the future — something like a supercharged Copilot.</p><h3>Anthony Shaw — PSF Fellow, Author of CPython Internals</h3><p>Anthony said AI is like the new Stack Overflow.</p><p>Earlier, people copied code from blogs or seniors. Now it’s from ChatGPT. AI is useful for boilerplate or things you already know. He uses Copilot Chat for regular stuff and agent mode when he’s working on something unfamiliar (like frontend work).<br>His advice: <em>Don’t blindly rely on AI</em>. If you don’t keep learning, the gap between juniors and seniors will grow fast.</p><h3><strong>Anthony Sottile — Maintainer of pre-commit, flake8, and pytest</strong></h3><p>He doesn’t use AI tools.</p><p>He said his problems are too complex for AI. It’s easier for him to just write the code than explain it to a chatbot.</p><p>He does agree that AI is good for boring or repetitive code.</p><h3>Reuven M. Lerner — Python Author &amp; Trainer</h3><p>Reuven said companies should <em>not</em> replace junior devs.</p><p>He said juniors are like seeds. If companies don’t invest in them now, they’ll struggle later when they only have senior devs and AI bots.</p><p>He uses AI mostly for writing-like reviewing posts or generating images. He rarely uses it for coding.</p><h3>Trey Hunner — Python Morsels</h3><p>Trey said AI won’t replace developers.</p><p>But it might change how we work. Developers might end up reading and reviewing more code instead of writing everything from scratch.</p><p>He doesn’t use Copilot or coding tools. He copies from ChatGPT when needed and uses a tool called Typingmind to talk to AI.</p><p>It is also worth a mention that Trey taught us the <a href="https://www.linkedin.com/redir/redirect?url=https%3A%2F%2Ftreyhunner%2Ecom%2F2015%2F06%2Fcabo-card-game%2F&amp;urlhash=WpQV&amp;trk=article-ssr-frontend-pulse_little-text-block">Cabo card game</a> during the evenings after PyCon.</p><h3>Samuel Colvin — Founder of Pydantic</h3><p>Samuel had a different view.<br>He said AI <em>will</em> replace some programmers.</p><p>Companies will use AI to do more with fewer people.<br>He sees AI as a way to speed things up and make work more efficient.</p><p>He uses tools like trae, cline, and others to boost his workflow.</p><h3>Simon Willison — Django co-creator, Creator of Datasette</h3><p>Simon said AI won’t replace developers. But it will create new types of work and improve productivity.</p><p>He uses Claude, ChatGPT, and his own LLM CLI tool. For personal scripts, he uses AI to get things done quickly, and reviews the code properly when it matters.</p><h3>Mariatta Wijaya — Python Core Developer</h3><p>Mariatta said AI is more helpful for senior developers.</p><p>Seniors can use AI to write code quickly and then fix what’s wrong. For juniors, it depends. If the task is small, AI can help. But juniors still need to understand what the code does.</p><p>She uses Copilot in her daily work.</p><p>She also recommends this talk from PyTexas:<br><a href="https://www.youtube.com/watch?v=FP9VoFPJsiQ">Heather’s Talk — How to Think Like a Senior Engineer</a></p><h3>Final Thoughts</h3><p>Most Python people agree: AI won’t replace developers anytime soon.</p><p>My thoughts: it <em>will</em> definitely change how we work.</p><p>If you’re using AI without understanding, you’ll likely fall behind. If you keep learning and adapt, you’ll do fine.</p><h3>My personal favorite moment</h3><p>One of the highlights of PyCon US for me was meeting <strong>Paul Everitt</strong>.</p><p>He gave me a sneak peek of the Python documentary trailer before it was released on YouTube. And even better-he handed me a chocolate Cornetto from the PyCharm booth while telling stories. Instant core memory.</p><p>Paul is one of the most enthusiastic and genuine people I met at the conference. A natural storyteller.</p><p>A few things I didn’t know about him until then:</p><ul><li>He managed <a href="http://navy.mil/">navy.mil</a> while serving in the U.S. military-one of the earliest websites on the internet.</li><li>He was a keynote speaker at the first-ever Python conference in 1994.</li><li>He helped incorporate the Python Software Foundation .</li><li>He was Guido’s manager during his Plone days.</li></ul><p>The kind of person you meet once and never forget.</p><p>That’s all from my hallway track this year.</p><p><em>Originally published at </em><a href="https://blog.adarshd.dev/posts/pycon-us-ai-and-future-of-programming/">https://blog.adarshd.dev/posts/pycon-us-ai-and-future-of-programming/</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c110748ccc22" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/will-ai-replace-junior-developers-i-asked-experts-at-pycon-us-c110748ccc22">Will AI Replace Junior Developers? I Asked Experts at Pycon US</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Local Data in Python]]></title>
            <link>https://python.plainenglish.io/thread-local-data-in-python-143b5bd4d3e0?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/143b5bd4d3e0</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[threading-in-python]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 11:29:45 GMT</pubDate>
            <atom:updated>2024-02-19T12:17:28.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_IXY37a-10Fdz06Csax-Q.jpeg" /></figure><p>Since threads in Python share the memory space of their parent process, we might need to define thread-specific variables for specific use cases to avoid unintended side effects.</p><p>In this article, we will:</p><ol><li>Explore Thread local storage: Python threading module’s solution for thread-specific/thread-private values.</li><li>See its real-world example from Open-Source ( usage in the Peewee ORM library).</li><li>Look at the CPython source code to see how thread local storage is implemented under the hood.</li></ol><h3>Background</h3><p>Threads share the memory space of their parent process. This will allow us to seamlessly access and share variables, data structures, etc., across threads. But this comes with its own challenges. There may be scenarios where we need to isolate variables and might need to store data specific to each thread. Thread local storage can be leveraged in this case.</p><p>We can use <a href="https://docs.python.org/3/library/threading.html#thread-local-data">local() found in the </a><a href="https://docs.python.org/3/library/threading.html#thread-local-data">threading module</a> to define thread-local variables.</p><pre>import threading<br>import time<br><br># Create a thread-local storage object (1)<br>thread_local = threading.local()<br><br><br>def init_data(number):<br>    thread_local.number = number * 100<br><br><br>def show_data():<br>    print(f&quot;Thread {threading.current_thread().name} has number {thread_local.number}&quot;)<br><br><br>def worker(number):<br>    init_data(number)<br><br>    for _ in range(3):<br>        time.sleep(1)<br>        show_data()<br><br><br>thread1 = threading.Thread(target=worker, name=&quot;A&quot;, kwargs={&quot;number&quot;: 1})<br>thread2 = threading.Thread(target=worker, name=&quot;B&quot;, kwargs={&quot;number&quot;: 2})<br><br>thread1.start()<br>thread2.start()<br><br>thread1.join()<br>thread2.join()</pre><p>The program output will be:</p><pre>Thread A has number 100<br>Thread B has number 200<br>Thread A has number 100<br>Thread B has number 200<br>Thread A has number 100<br>Thread B has number 200</pre><p>As seen in comment #(1), a thread-local storage object was created and assigned to the variable thread_local. Arbitrary attributes can be assigned to this variable, which are specific to the thread that performs the assignment and is isolated from others.</p><p>In the example, each thread stores its own number attribute to the thread_local object and accesses the thread-specific value during their concurrent execution.</p><h3>Usage in the Wild</h3><p>Peewee, a Python ORM, utilizes thread-local data in its ThreadSafeDatabaseMetadata to support dynamic database switches at runtime in multithreaded applications.</p><p>The source code can be found <a href="https://github.com/coleifer/peewee/blob/01b2d94a4029858b9d2b1bee6fac40eed27ad9ad/playhouse/shortcuts.py#L322">here.</a></p><pre># File: peewee/playhouse/shortcuts.py<br><br>class ThreadSafeDatabaseMetadata(Metadata):<br>    &quot;&quot;&quot;<br>    Metadata class to allow swapping database at run-time in a multi-threaded<br>    application. To use:<br><br>    class Base(Model):<br>        class Meta:<br>            model_metadata_class = ThreadSafeDatabaseMetadata<br>    &quot;&quot;&quot;<br><br>    def __init__(self, *args, **kwargs):<br>        # The database attribute is stored in a thread-local.<br>        self._database = None<br>        self._local = threading.local()<br>        super(ThreadSafeDatabaseMetadata, self).__init__(*args, **kwargs)<br><br>    def _get_db(self):<br>        return getattr(self._local, &quot;database&quot;, self._database)<br><br>    def _set_db(self, db):<br>        if self._database is None:<br>            self._database = db<br>        self._local.database = db<br><br>    database = property(_get_db, _set_db)</pre><p>In multithreaded applications using peewee ORM, database switching at runtime without using ThreadSafeDatabaseMetada can lead to errors. If multiple threads work in parallel and one thread changes the connection parameters, this can lead to errors such as writing to a wrong DB, inconsistent writes (in case of non-atomic DB operations), etc.</p><p>ThreadSafeDatabaseMetada solves this by keeping the database attributes in a thread-local object ( self._local). In this way, dynamic changes to the database will only affect the thread that made the change. Other threads will keep working with their existing databases.</p><h3>Should I use it?</h3><p>Thread-local storage should be used when:</p><p>You are writing a multi-threaded application (obviously) and:</p><ul><li>If some variables are used by the current thread only and are not relevant to the main thread/other threads.</li><li>You find out that changes made by one thread can lead to unintended side effects in other concurrent threads.</li></ul><p>Generally, if you are working with multiple threads and there is shared mutable data:</p><p>You should check if sharing these data across threads is actually needed.</p><ol><li>If sharing can be avoided, use thread-local storage to make the data specific to each thread.</li><li>Otherwise, implement locks or other synchronization primitives to enforce thread safety.</li></ol><p><strong>Note</strong>: Context variables from the <a href="https://docs.python.org/3.12/library/contextvars.html#module-contextvars">contextvars standard library module</a> can be used as an alternative to threading.local(). They work with multithreading as well as asyncio to store context-specific information. In the case of asyncio programs, context variables allow each coroutine task to have its own set of variables isolated from other (asyncio) tasks.</p><h3>Behind the scenes</h3><p>The Python implementation of threading.local can be found in the <a href="https://github.com/python/cpython/blob/3.12/Lib/_threading_local.py">/Lib/_threading_local.py path in CPython source code.</a></p><p>The _localimpl class is used to store thread-local values.</p><pre>class _localimpl:<br>    &quot;&quot;&quot;A class managing thread-local dicts&quot;&quot;&quot;<br>    __slots__ = &#39;key&#39;, &#39;dicts&#39;, &#39;localargs&#39;, &#39;locallock&#39;, &#39;__weakref__&#39;<br><br>    def __init__(self):<br>        # The key used in the Thread objects&#39; attribute dicts.<br>        # We keep it a string for speed but make it unlikely to clash with<br>        # a &quot;real&quot; attribute.<br>        self.key = &#39;_threading_local._localimpl.&#39; + str(id(self))<br>        # { id(Thread) -&gt; (ref(Thread), thread-local dict) }<br>        self.dicts = {}</pre><p>The dicts attribute maps the id of a thread to a tuple. The tuple is two-membered, containing a reference to the thread and the actual dictionary storing thread local values (# { id(Thread) -&gt; (ref(Thread), thread-local dict) }).</p><p>Looking at a few other methods of the class:</p><pre>class _localimpl:<br>    &quot;&quot;&quot;A class managing thread-local dicts&quot;&quot;&quot;<br>    def get_dict(self):<br>        &quot;&quot;&quot;Return the dict for the current thread. Raises KeyError if none<br>        defined.&quot;&quot;&quot;<br>        thread = current_thread()<br>        return self.dicts[id(thread)][1] # (1) returning the local dict of current thread<br><br>    def create_dict(self):<br>        &quot;&quot;&quot;Create a new dict for the current thread, and return it.&quot;&quot;&quot;<br>        localdict = {}<br>        key = self.key<br>        thread = current_thread()<br>        idt = id(thread)<br>        ...<br>        wrthread = ref(thread, thread_deleted)<br>        thread.__dict__[key] = wrlocal<br>        self.dicts[idt] = wrthread, localdict  # (2) Populating the `dicts` with a new thread<br>        return localdict</pre><p>The comments #(1) &amp; #(2) illustrate operations on the dicts attribute discussed previously.</p><p>(1): Returns the local data dictionary corresponding to the current thread accessing it.</p><p>(2): This part initializes the local dict for a new thread.</p><p>Then, we have the actual local callable, which we call as threading.local() to initialize a thread-local object.</p><pre>@contextmanager<br>def _patch(self):<br>    impl = object.__getattribute__(self, &#39;_local__impl&#39;)<br>    try:<br>        dct = impl.get_dict()  # (3) this will return local dict of current thread -/<br>                               # see its definition in the above snippet<br>    except KeyError:<br>        ...<br>        # calls _localimpl`s create_dict to create &amp; init a new dict<br>    with impl.locallock:<br>        object.__setattr__(self, &#39;__dict__&#39;, dct) # (4) &lt;The magic&gt; Temporarily replaces -/<br>        # the instance&#39;s __dict__ attribute with the thread-specific dictionary.<br>        <br>        yield<br><br><br>class local:<br>    __slots__ = &#39;_local__impl&#39;, &#39;__dict__&#39;<br><br>    def __new__(cls, /, *args, **kw):<br>        ...<br><br>        impl = _localimpl()  # (1) - wraps the _localimpl object in an attribute<br>        impl.localargs = (args, kw)<br>        impl.locallock = RLock()  # (2) - Lock for thread safety<br>        object.__setattr__(self, &#39;_local__impl&#39;, impl)<br>        # We need to create the thread dict in anticipation of<br>        # __init__ being called, to make sure we don&#39;t call it<br>        # again ourselves.<br>        impl.create_dict()<br>        return self<br><br>    def __getattribute__(self, name):<br>        with _patch(self):<br>            return object.__getattribute__(self, name)<br><br>    def __setattr__(self, name, value):<br>        if name == &#39;__dict__&#39;:<br>            raise AttributeError(<br>                &quot;%r object attribute &#39;__dict__&#39; is read-only&quot;<br>                % self.__class__.__name__)<br>        with _patch(self):<br>            return object.__setattr__(self, name, value)<br><br>    ...</pre><p>Let’s look at various parts of the code one by one.</p><p># (1): An object of _localimpl class is created and later stored in _local__impl attribute</p><p># (2): RLock() is used on dict operations - Concurrent writes by multiple threads may cause &#39;lost writes&#39; since dict is not thread-safe.</p><p># (3): In the try/except block, the current thread&#39;s local data is fetched and assigned to the variable named dct.</p><p># (4): The magic happens here. Here is a quick refresher on class attributes before we delve further:</p><blockquote><em>A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C. </em><strong><em>dict</em></strong><em>[“x”] (although there are a number of hooks which allow for other means of locating attributes).</em></blockquote><p>The _patch function we are currently in is a context manager. Using the line marked as # (4), it patches the namespace dictionary of the local class with the dot variable (which stores the current-thread specific data).</p><p>Since the __getattribute__ and __setattr__ dunders of the class local use the _patch context manager, attribute access performed inside the context will use the thread-local dictionary ( dct) replacing the class&#39;s actual namespace dictionary.</p><p><strong>Note</strong>: The Lib/_threading_local.py starts with the below note:</p><blockquote><em>Note that this module provides a Python version of the threading.local class. Depending on the version of Python you’re using, there may be a faster one available. You should always import the </em><em>local class from </em><em>threading.</em></blockquote><p>The code we looked at might not be the one running in our Python installations. I think newer Pythons versions are using C implementations of the thread local functionality for efficiency.</p><p>I share interesting Python snippets 🐍 like this from open-source projects illustrating Python language features in my newsletter, “Python in the Wild”.</p><p>Subscribe to the newsletter on <a href="https://adarshd.substack.com/">Substack</a> or <a href="https://www.linkedin.com/newsletters/python-in-the-wild-7155981512197181440/">Linkedin</a> to receive new Pythonic posts to your email 💌🚀.</p><p><em>Originally published at </em><a href="https://blog.adarshd.dev/posts/thread-local-storage-in-python/"><em>https://blog.adarshd.dev</em></a><em> on February 18, 2024.</em></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=143b5bd4d3e0" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/thread-local-data-in-python-143b5bd4d3e0">Thread Local Data in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolution of the Sort in Python and the Role of functools.cmp_to_key]]></title>
            <link>https://python.plainenglish.io/evolution-of-the-sort-in-python-and-the-role-of-functools-cmp-to-key-a5f8bbbb033a?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f8bbbb033a</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 13:29:05 GMT</pubDate>
            <atom:updated>2024-02-06T10:17:25.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lb5G5f5tKHC3HEdA6Ewr9Q.jpeg" /></figure><p>In Python, the sort method and the sorted callable are commonly used for sorting operations. sort is a list method that modifies the list in place, whereas sorted takes an iterable as its first argument and returns a sorted list containing the iterable’s elements.</p><p>Both of these use the <a href="https://en.wikipedia.org/wiki/Timsort">Timsort algorithm</a> under the hood to perform the sorting operation.</p><p>In this article, we will explore the evolution of sorting in Python from Python 2 to 3 and look into the cmp_to_key function from functools.</p><h3>Background</h3><p>Below are the type annotations for sort and sorted, from the <a href="https://github.com/python/typeshed/blob/2c295057659d2b8bdfe632012c04497273b002b6/stdlib/builtins.pyi#L1665">Python typeshed library</a>.</p><pre>@overload<br>def sorted(<br>    __iterable: Iterable[SupportsRichComparisonT],<br>    *,<br>    key: None = None,<br>    reverse: bool = False<br>) -&gt; list[SupportsRichComparisonT]:<br>    ...<br><br><br>@overload<br>def sorted(<br>    __iterable: Iterable[_T],<br>    *,<br>    key: Callable[[_T], SupportsRichComparison],<br>    reverse: bool = False<br>) -&gt; list[_T]:<br>    ...<br><br><br>class list(MutableSequence[_T]):<br>    @overload<br>    def sort(<br>        self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False<br>    ) -&gt; None:<br>        ...<br><br>    @overload<br>    def sort(<br>        self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False<br>    ) -&gt; None:<br>        ...</pre><p>Both sort and sorted accept an optional keyword-only argument key. It should be a callable and if supplied, will be used to calculate the comparison key.</p><blockquote><em>From Python docs:</em></blockquote><blockquote>key<em> specifies a function of one argument that is used to extract a comparison key from each list element (for example, </em><em>key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process.</em></blockquote><p>Now let’s take a look at the <a href="https://docs.python.org/2.7/library/functions.html?highlight=sort#sorted">Python 2 docs for the sorted built-in</a>:</p><pre>sorted(iterable[, cmp[, key[, reverse]]])<br><br>    Return a new sorted list from the items in iterable.<br><br>    The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).<br><br>    cmp specifies a custom comparison function of two arguments (iterable elements), <br>    which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument.<br>    <br>    ...</pre><p>There is an additional argument cmp compared to what we have seen in Python 3.</p><p>The docs also mention:</p><blockquote><em>In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.</em></blockquote><p>The cmp argument was removed in Python 3, and the <a href="https://docs.python.org/3/library/functools.html#functools.cmp_to_key">cmp_to_key helper</a> to convert comparison functions to new-style key functions has been added to the functools module.</p><h3>Usage in the Wild</h3><p>If we have a comparison function (which takes two arguments and returns their comparison result), this can be converted to a sort key by using cmp_to_key function — provided in the functools module.</p><p>The below example from the <a href="https://github.com/craffel/pretty-midi">pretty_midi</a>, a MIDI processing library illustrates the use of cmp_to_key.</p><p><a href="https://github.com/craffel/pretty-midi/blob/07f4174ef701c3355fb6d4aa72ae968026d5df10/pretty_midi/pretty_midi.py#L1473">Link to source code</a></p><pre>class PrettyMIDI(object):<br>    &quot;&quot;&quot;A container for MIDI data in an easily-manipulable format.&quot;&quot;&quot;<br><br>    ...<br><br>    def write(self, filename):<br>        &quot;&quot;&quot;Write the MIDI data out to a .mid file.&quot;&quot;&quot;<br><br>        def event_compare(event1, event2): # &lt;--- (1)<br>            &quot;&quot;&quot;Compares two events for sorting.<br><br>            Events are sorted by tick time ascending. Events with the same tick<br>            time ares sorted by event type. Some events are sorted by<br>            additional values. For example, Note On events are sorted by pitch<br>            then velocity, ensuring that a Note Off (Note On with velocity 0)<br>            will never follow a Note On with the same pitch.<br><br>            Parameters<br>            ----------<br>            event1, event2 : mido.Message<br>               Two events to be compared.<br>            &quot;&quot;&quot;<br><br>            secondary_sort = {<br>                &quot;set_tempo&quot;: lambda e: (1 * 256 * 256),<br>                &quot;time_signature&quot;: lambda e: (2 * 256 * 256),<br>                &quot;key_signature&quot;: lambda e: (3 * 256 * 256),<br>                &quot;lyrics&quot;: lambda e: (4 * 256 * 256),<br>                &quot;text_events&quot;: lambda e: (5 * 256 * 256),<br>                &quot;program_change&quot;: lambda e: (6 * 256 * 256),<br>                &quot;pitchwheel&quot;: lambda e: ((7 * 256 * 256) + e.pitch),<br>                &quot;control_change&quot;: lambda e: (<br>                    (8 * 256 * 256) + (e.control * 256) + e.value<br>                ),<br>                &quot;note_off&quot;: lambda e: ((9 * 256 * 256) + (e.note * 256)),<br>                &quot;note_on&quot;: lambda e: ((10 * 256 * 256) + (e.note * 256) + e.velocity),<br>                &quot;end_of_track&quot;: lambda e: (11 * 256 * 256),<br>            }<br>            # If the events have the same tick, and both events have types<br>            # which appear in the secondary_sort dictionary, use the dictionary<br>            # to determine their ordering.<br>            if (<br>                event1.time == event2.time<br>                and event1.type in secondary_sort<br>                and event2.type in secondary_sort<br>            ):<br>                return (secondary_sort[event1.type](event1) - <br>                        secondary_sort[event2.type](event2))<br><br>            # Otherwise, just return the difference of their ticks.<br>            return event1.time - event2.time<br><br>        # Create track 0 with timing information<br>        timing_track = mido.MidiTrack()<br><br>        ...  # Code processing the timing_track<br><br>        # Sort the (absolute-tick-timed) events.<br>        timing_track.sort(key=functools.cmp_to_key(event_compare)) # &lt;--- (2)<br><br>        ...</pre><p>The event_compare function (pointed out in comment (1)) provides a specific comparison logic for MIDI events, ensuring they are sorted correctly by their tick time and type and additional criteria for certain event types. Then, functools.cmp_to_key is used to convert this comparison function into a key function ( pointed out in comment (2)).</p><h3>Should You Use It</h3><p>As cmp_to_key was aimed to help transition from Python 2 style cmp functions to key functions, its usage is not very common in newer projects. However, it can come in handy when we already have a comparison function defined in our code to compare two objects and need to sort an iterable of these objects. In such a case, cmp_to_key will allow us to reuse our comparison logic (defined in our comparison function) without defining a new key function.</p><h3>Behind the Scenes</h3><p>Below is the <a href="https://github.com/python/cpython/blob/87cd20a567aca56369010689e22a524bc1f1ac03/Lib/functools.py#L207">source code of </a><a href="https://github.com/python/cpython/blob/87cd20a567aca56369010689e22a524bc1f1ac03/Lib/functools.py#L207">cmp_to_key</a> from the functools module</p><pre>def cmp_to_key(mycmp):<br>    &quot;&quot;&quot;Convert a cmp= function into a key= function&quot;&quot;&quot;<br>    class K(object):<br>        __slots__ = [&#39;obj&#39;]<br>        def __init__(self, obj):<br>            self.obj = obj<br>        def __lt__(self, other):<br>            return mycmp(self.obj, other.obj) &lt; 0<br>        def __gt__(self, other):<br>            return mycmp(self.obj, other.obj) &gt; 0<br>        def __eq__(self, other):<br>            return mycmp(self.obj, other.obj) == 0<br>        def __le__(self, other):<br>            return mycmp(self.obj, other.obj) &lt;= 0<br>        def __ge__(self, other):<br>            return mycmp(self.obj, other.obj) &gt;= 0<br>        __hash__ = None<br>    return K</pre><p>cmp_to_key intelligently maps the original comparison function to a key function suitable for sorting by implementing all the comparison dunders.</p><p>It returns a new callable (class K) with all the comparison dunders, which will be called during the sorting process to calculate the sort key. Since the sorting process compares each of the calculated keys, the comparison dunders will get invoked, and they will return based on the result from the original comparison function.</p><p>For example, during sorting, when K object &lt; another K object needs to be checked, Python will actually call the lt dunder method on K. This method simply calls the original cmp function to compare the obj attributes of the two K instances.</p><p>I share interesting Python snippets 🐍 like this from open-source projects illustrating Python language features in my newsletter, “Python in the Wild”.</p><p>Subscribe to the newsletter on <a href="https://adarshd.substack.com/">Substack</a> or <a href="https://www.linkedin.com/newsletters/python-in-the-wild-7155981512197181440/">Linkedin</a> to receive new Pythonic posts to your email 💌🚀.</p><p><em>Originally published at </em><a href="https://blog.adarshd.dev/posts/evolution-of-python-sort-and-cmp_to_key/"><em>https://blog.adarshd.dev</em></a><em> on February 5, 2024.</em></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f8bbbb033a" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/evolution-of-the-sort-in-python-and-the-role-of-functools-cmp-to-key-a5f8bbbb033a">Evolution of the Sort in Python and the Role of functools.cmp_to_key</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partition method of Python strings]]></title>
            <link>https://medium.com/@adarshd/partition-method-of-python-strings-ef791cde9dc3?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef791cde9dc3</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 06:04:58 GMT</pubDate>
            <atom:updated>2024-01-23T06:04:58.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AMo5SeNOoN81sDYr.png" /></figure><p>The partition method of str covers a niche use case — It is useful when a string needs to be split into exactly two parts based on a separator. It returns a three-membered tuple containing the part before, the separator itself, and the part after the separator.</p><p>The split method is commonly used for splitting strings, which returns a list whose length can change based on the number of times the separator is present.</p><pre>host = &quot;localhost:8000&quot;<br>print(host.split(&quot;:&quot;))  <br># Output: [&#39;localhost&#39;, &#39;8000&#39;]<br><br>host = &quot;localhost&quot;<br>print(host.split(&quot;:&quot;))  <br># Output: [&#39;localhost&#39;]<br><br>host = &quot;&quot;<br>print(host.split(&quot;:&quot;))  <br># Output: [&#39;&#39;]</pre><p>partition is helpful when we need to get precisely two parts from a string using a separator. It returns a three-membered tuple containing the part before, the separator itself (if a match is found, else empty string), and the part after the separator.</p><pre>server_name = &quot;localhost:5000&quot;<br>print(server_name.partition(&quot;:&quot;))  <br># Output: (&#39;localhost&#39;, &#39;:&#39;, &#39;5000&#39;)<br><br>server_name = &quot;localhost&quot;<br>print(server_name.partition(&quot;:&quot;))  <br># Output: (&#39;localhost&#39;, &#39;&#39;, &#39;&#39;)<br><br>server_name = &quot;&quot;<br>print(server_name.partition(&quot;:&quot;))  <br># Output: (&#39;&#39;, &#39;&#39;, &#39;&#39;)</pre><p>Using partition instead of splitsaves us from additional checks on the result&#39;s length when exactly two parts are required.</p><p>Flask uses the partition method to determine the host and port to use when running the Flask app. You can see the <a href="https://github.com/pallets/flask/blob/7b5e176d1ab23e183d0403573358299ed6562dce/src/flask/app.py#L588">source code here</a>.</p><p>A simplified version of the code is added below.</p><pre>def run(<br>    self,<br>    host: str | None = None,<br>    port: int | None = None,<br>    debug: bool | None = None,<br>    load_dotenv: bool = True,<br>    **options: t.Any,<br>) -&gt; None:<br>    ...<br><br>    server_name = self.config.get(&quot;SERVER_NAME&quot;)<br>    sn_host = sn_port = None<br><br>    if server_name:<br>        sn_host, _, sn_port = server_name.partition(&quot;:&quot;)<br>        # The `partition` method will always return a three-membered tuple<br><br>    if not host:<br>        if sn_host:<br>            host = sn_host<br>        else:<br>            host = &quot;127.0.0.1&quot;<br><br>    if port or port == 0:<br>        port = int(port)<br>    elif sn_port:<br>        port = int(sn_port)<br>    else:<br>        port = 5000</pre><p>Here, the server_name string is partitioned into host and port values.</p><p>I share interesting Python snippets 🐍 like this from open-source projects illustrating Python language features. Subscribe to my newsletter (<a href="https://adarshd.substack.com/">https://adarshd.substack.com</a>) get new posts delivered to your email 💌🚀.</p><p><em>Originally published at </em><a href="https://adarshd.substack.com/p/partition-method-of-python-strings"><em>https://adarshd.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef791cde9dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When I met Guido van Rossum]]></title>
            <link>https://medium.com/@adarshd/when-i-met-guido-van-rossum-6e9ddc17c0d2?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e9ddc17c0d2</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[guido-van-rossum]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[conference]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 12:30:41 GMT</pubDate>
            <atom:updated>2023-10-06T18:21:48.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtYT3Xt49tglUwwE04xIwg.jpeg" /></figure><p>This is my account of meeting Guido Van Rossum and his advice on becoming a Python Core Developer.</p><p>This interaction is a few months old and happened during Pycascades in Vancouver (18–19 March 2023). Yesterday a random thought about this interaction crossed my mind and I thought I should write a blog post on this.</p><h3>Pycascades &amp; Python Conferences</h3><p>I flew from India to Vancouver to Speak at Pycascades to speak on “Metaprogramming in Python using Metaclasses”</p><blockquote><strong>My Talk: </strong>If you are interested in the talk, take this digression.</blockquote><blockquote><a href="https://speakerdeck.com/adarshd/metaprogramming-in-python-using-metaclasses">Slides</a> &amp; <a href="https://www.youtube.com/watch?v=-js0K7Q878c">Talk Video</a>. Pardon my lack of preparation, I was busy exploring Vancouver the previous day.</blockquote><p>I would broadly classify tech conferences into two types: Busy vs. Relaxed conferences.</p><p>A typical busy conference will have a large number of attendees, multiple parallel tracks, and a whole lot of things going around at the same time. Relaxed conferences have a maximum of a few hundred attendees, there is only a single track and everything occurs at a relaxed pace.</p><p>I would classify Pycascades ’23 as a relaxed conference. In a typical busy conference, you will have to line up to meet your favorite tech rockstar. But here that was not the case. This was the first “relaxed” conference I have been to and was a bit surprising.</p><h3>Meeting Guido</h3><p>I had my presentation at 3 PM on day 1 of the conference. I mostly spend my day in the speaker-ready room doing some last-minute preparations. After completing my talk I went on to get some snacks during the evening break.</p><p>There he was. I did a quick Google image search and to double-check, I even asked a volunteer to confirm if that was Guido himself.</p><p>I don’t exactly remember when I heard about Guido for the first time. This might be from my high school where our computer teacher instilled in us a love for programming or in the first semester of my Bachelors where we had an introductory course in Python.</p><p>I mustered up enough courage to talk to him and thanks to Pycascades being a relaxed conference, there was no one around waiting to talk to him. He told me that he listened to the last few slides of my talk and wanted to know how I got into metaprogramming.</p><p>This was a part of his character. He always asks ‘Why’. Before answering a question, he wanted to know the motive or the origin of the question. I guess this curiosity is one factor that sets apart great developers from good developers.</p><p>Here is a brief of the conversation we had on that day(reworded and mostly taken from my memory).</p><p><em>Guido</em>: I missed the initial parts of your talk. I came when you reached slide X(a slide towards the end). How did you get into the idea of metaprogramming?</p><p><em>Me</em>: We have a knowledge-sharing session in our company. I presented an initial version of this talk there. Also, I love teaching others and I explore new topics from Realpython and blogs.</p><p><em>Guido</em>: At your day job, what are you currently working on? Are you using Python?</p><p><em>Me</em>: Yes. I am building a GraphQL API powering the backend of a travel application.</p><p><em>Guido</em>: GraphQL? Is that the Facebook library?</p><p><em>Me</em>: Yes. We are using the Graphene-Python library.</p><p><em>Guido</em>: I see. So there are Python wrappers around it.</p><blockquote>Python is vast:</blockquote><blockquote>I met a lot of experts at the conference and everyone has their areas of expertise. Also, I had a similar discussion with Sarah Kaiser from Microsoft where she talked about the vastness of Python. There are experts in Web (API devs), PyData, ML, etc. and in most cases, everyone has an exclusive area of expertise. From my conversation with Guido, I was surprised to see that he was unaware of GraphQL libraries, but considering the fact that his expertise is in core development, this is nothing surprising.</blockquote><p>Then I asked him a few questions which came to my mind:</p><p><em>Q1</em>: I asked a question regarding alternate Python implementations. Something along the lines of “Do you see Pypy overtaking CPython anytime in the future?”</p><p><em>Guido</em>: PyPy or any other implementations won’t be replacing CPython. Alternate implementations are always trying to catch up with the CPython releases. With the Faster CPython Project, future releases have improved performance reducing the need for alternative implementations, if speed is the concern. Jit compiler</p><p><em>Q2</em>: Will you be coming to India for our Pycon event (Pycon India)</p><p><em>Guido</em>: I most probably won’t be there since I am not able to travel that long. (I don’t exactly remember the wording)</p><p><em>Q3</em>: I work in a young team of Backend devs using Python. Do you have any advice for getting better at Python Programming?</p><p>(I only remember a part of this answer)</p><p><em>Guido</em>:</p><ol><li>Be a part of local Python communities</li><li>Read more code than you write</li></ol><p>Expanding on point 2, reading good code is a great way to learn new patterns and expand our thinking approaches towards problems. I recently came across “death and gravity” blog with two great resources for the same.</p><p><a href="https://death.andgravity.com/stdlib">Learn by reading code: Python standard library design decisions explained</a> and <a href="https://death.andgravity.com/aosa">Struggling to structure code in larger programs? Great resources a beginner might not find so easily</a></p><p>I stopped when I ran out of questions to ask.</p><p>Initially I had told him that I love teaching. He asked me to connect with the RealPython team (who were present at the conference) and collaborate with them on some tutorials.</p><p>Then we took a selfie (The cover image of this post). Also, I was surprised no one else was doing the same (relaxed conference!).</p><p>I noted down important points of the conversation to share with my teammates, which became useful when writing this.</p><h3>How to be a CPython Core Developer</h3><p>On day 2, the final day of the conference, I arrived at the venue (SFU Vancouver campus) with a resolve not to miss any of the talks like I did yesterday owing to my talk preparation.</p><p>On the morning break, I saw Guido talking to a volunteer regarding Pycon. I was ready with my new set of questions.</p><p>I was looking to advance my Python knowledge and was looking to go deeper into CPython implementation. I had my copy of <a href="https://realpython.com/products/cpython-internals-book/">Cpython Internal Book</a> and have taken a peek into the <a href="https://devguide.python.org/">Python Devguide</a> and wanted to get an idea of the next steps to take from the creator himself.</p><blockquote>If you are new to the below terms, please refer to the listed resources</blockquote><blockquote><strong>What is CPython</strong></blockquote><blockquote>Read <a href="https://realpython.com/cpython-source-code-guide/">this guide</a> by Realpython team</blockquote><blockquote><strong>Who are CPython core developers</strong></blockquote><blockquote><a href="https://speakerdeck.com/mariatta/what-is-a-python-core-developer">Talk by Mariatta</a> &amp; <a href="https://devguide.python.org/core-developers/become-core-developer/">Devguide page</a></blockquote><p>I went ahead and asked Guido, “How can I become a core developer”?</p><p>The hall was a bit crowded and noisy at that time. Guido insisted we move to a quieter side and talk. He grabbed a snack, went to a quiet corner overlooking the Vancouver harbor and asked:</p><p>Why?</p><p>Why do you want to be a core dev? Becoming one is a decision many would regret.</p><p>I didn’t quite understand this at that time. It made sense recently when I was reading the BDFL retirement mail thread from the Python mailing list archive at 3 AM. Also see <a href="https://snarky.ca/the-social-contract-of-open-source/">this article</a> from Brett Cannon.</p><p>Going back to the topic:</p><p>I somehow evaded his whys and got the answer from him.</p><p>Here are some of the points he mentioned as a part of his answer:</p><ul><li>Be active in discussion forums.</li></ul><p><a href="https://www.python.org/community/lists/">Python mailing lists</a></p><p><a href="https://discuss.python.org/">Python Discourse</a></p><ul><li>Look for issues or new features to be added to the standard library</li></ul><p>Since I was already using Python, he asked me to identify bugs/improvements and try to work on those.</p><blockquote><em>Fun fact: Currently, more than 63% of </em><a href="https://github.com/python/cpython/tree/3.12"><em>CPython source</em></a><em> is written in Python. Knowledge of C is not required to contribute to CPython.</em></blockquote><p>I was happy and relieved hearing this (There are little bugs everywhere, even in CPython). Maybe because I can justify the bugs I create using this statement.</p><ul><li>Never give up</li></ul><p>Once started, we should go on taking up issues and continue contributing.</p><ul><li>Multiple Ways to Contribute:</li></ul><p>Along with contributing code, we can also take part in discussions, writing docs, or reviewing PRs.</p><p>Then came the surprising move. He wanted to check how ChatGPT would answer this (no I am not making this up). He pulled in his laptop, logged in to ChatGPT, and asked the same question.</p><p>I do not remember exactly the answer it gave, I remember it had a link to the dev guide and some other instructions. He found out that there was a mistake in the answer and reported that and ChatGPT responded with a revised(and correct) answer.</p><h3>Lessons Learnt</h3><ul><li>Go to conferences:</li></ul><p>Pycascades was a very enriching experience for me. I would recommend everyone to go to conferences. I connected &amp; exchanged ideas with many great folks (VSCode-Python Team, RealPython Team, Mariatta, and so many more awesome people)</p><ul><li>Be nice:</li></ul><p>There were common traits I observed whenever I spoke with most of the experts during relaxed as well as busy conferences. They all are humble, welcoming, willing to help and genuinely care about others.</p><p>Looking back on this journey, everything was worth it — the 16-hour long flight, taking a week-long leave from work (and handling the production credentials to juniors)</p><h3>Thanks to Pysacsades</h3><p>It isn’t fair to end this post without thanking <a href="https://2023.pycascades.com/about/team/">Pycascades Team</a> for giving me a speaker invite and covering a part of the travel expenses.</p><p>Special thanks to Eliza, Ben, Jolene, and the entire Pycascades team for running this awesome conference.</p><p><em>Originally published at </em><a href="https://blog.adarshd.dev/posts/when-i-met-guido-van-rossum/"><em>https://blog.adarshd.dev</em></a><em> on October 5, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e9ddc17c0d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Safety in Python]]></title>
            <link>https://python.plainenglish.io/thread-safety-in-python-7441f8627d46?source=rss-e0535497e40------2</link>
            <guid isPermaLink="false">https://medium.com/p/7441f8627d46</guid>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[thread-safety]]></category>
            <dc:creator><![CDATA[Adarsh Divakaran]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 06:16:45 GMT</pubDate>
            <atom:updated>2024-06-20T17:17:21.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Before getting started with Thread safety, let’s look into race conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qKkkFH3q_ObZ0IP4" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Race Conditions</h3><p>From Wikipedia:</p><blockquote><em>A race condition or race hazard is the condition of an electronics, software, or other system where the system’s substantive behavior is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when one or more of the possible behaviors is undesirable.</em></blockquote><blockquote><em>Race conditions can occur especially in logic circuits, multithreaded, or distributed software programs.</em></blockquote><p>For an example of a race condition on a real-world web app, see this disclosed security bug: <a href="https://hackerone.com/reports/759247](https://hackerone.com/reports/759247)">https://hackerone.com/reports/759247</a></p><p>Here the hacker could redeem a gift card (intended for single use) multiple times.</p><p>A developer may think of implementing a gift card redemption flow like below:</p><p>1. Get a gift card code from the user</p><p>2. Validate the code: Check if it exists in DB, is not expired, and is not used.</p><p>3. If validation succeeds, add the gift card value to the user’s wallet and mark the gift card as used in the DB.</p><p>Think of the case where a user sends multiple requests at the same time. All parallel requests arriving before the execution of step 3, could succeed and can result in adding the gift card amount to the user’s wallet once per request. This might have happened in the case of the above bug.</p><h3>Threading in Python</h3><p>Threading is a method to implement concurrency in Python programs. Due to the presence of CPython’s GIL, threading is helpful in the case of I/O Bound programs.</p><p>threading module and concurrent.future’s ThreadPoolExecutor helper is commonly used to implement multithreading in Python.</p><p>Let’s dive into some Python examples after exploring the levels of thread safety.</p><h3>Levels of thread safety</h3><p>From Wikipedia, levels of thread safety:</p><blockquote><em>Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously.</em></blockquote><blockquote><em>Conditionally safe: Different threads can access different objects simultaneously, and access to shared data is protected from race conditions.</em></blockquote><blockquote><em>Not thread-safe: Data structures should not be accessed simultaneously by different threads.</em></blockquote><h3>Race conditions in Python Threaded Programs</h3><p><strong>Example 1: Incrementing a counter</strong></p><pre>import concurrent.futures<br>count = 0<br><br>def increase_counter():<br>    global count<br>    for i in range(1000):<br>        count += 1<br>with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:<br>    for _ in range(10_000):<br>        executor.submit(increase_counter)<br>print(F&quot;{count=}&quot;)</pre><p>The expected value of the count is 10,000 * 1000.</p><p>Running with Python 3.9, the program output varies per execution and gives outputs like below:</p><p>1. count=2163149</p><p>2. count=5642376</p><p>From this, we can conclude that the program is not thread-safe, since it gives unexpected results when run using multiple threads.</p><p>In the above examples, there are at most 10 parallel threads working since we have given max_workers=10</p><p>On adjusting max_workers value,</p><p>When max_workers=3, the output varies like below:</p><p>1. count=10000000</p><p>2. count=9999000</p><p>On reducing max_workers, which is the number of threads running in parallel, there is a visible reduction in errors, and at times, the expected output is also returned.</p><p>Consider the above scenario where each thread reads a variable and increments its value with 1. Between reads and writes, context switches to different threads can happen.</p><p>With multiple threads, the following scenario may be possible:</p><p>1. Thread_1 reads the value of count, gets 0</p><p>2. At the same time thread 2 reads count, and gets 0</p><p>3. Thread_1 sets count=count+1, as 1.</p><p>4. Thread_3 reads count, gets 1.</p><p>5. Thread_3 sets count=count+1, as 2</p><p>6. Thread_2 sets count=count+1, as 1 (since thread_2 holds a stale value of count, i.e., 0)</p><p>This explains the counter value being far less than expected.</p><p><strong>Example 2: Singleton class in Python</strong></p><p>Let’s take an example of a Singleton class created using Python.</p><p>Singleton pattern is used to make sure that only one instance is created for a class. This can be used in cases where the class initialization performs some steps which should be performed exactly once. Singletons are useful in cases where there are restrictions on certain resource usage such as concurrent connection limits.</p><p>Below is a commonly used example for a Singleton class in Python:</p><pre>class SingletonClass:<br>    def __new__(cls):<br>        if not hasattr(cls, &#39;instance&#39;):<br>            cls.instance = super(SingletonClass, cls).__new__(cls)<br>        return cls.instance<br><br>obj1 = SingletonClass()<br>obj2 = SingletonClass()<br>print(obj1 is obj2) # True<br>print(id(obj1)) # 2402721138768<br>print(id(obj2)) # 2402721138768</pre><p>In the above example, it is possible because two threads can evaluate the if check for instance (`if not hasattr(cls, ‘instance’)`) at near similar times and proceed to create two new objects.</p><p><strong>Example 3: The print function</strong></p><pre>from concurrent import futures<br><br>def printer():<br>    print(&#39;testing thread safety of print&#39;)<br><br>with futures.ThreadPoolExecutor(max_workers=10) as executor:<br>    for _ in range(10):<br>        executor.submit(printer)</pre><p>Output can vary from expected:</p><pre>testing thread safety of print<br>testing thread safety of print<br>testing thread safety of printtesting thread safety of print<br>testing thread safety of print<br><br>testing thread safety of printtesting thread safety of print<br>testing thread safety of print<br>testing thread safety of print<br><br>testing thread safety of print</pre><p>Before printing ending newlines, context switches happen sometimes printing output from another thread.</p><h3>Making programs thread-safe</h3><p><strong>Synchronization primitives</strong></p><p>The below synchronization primitives can be used to make a program thread safe.</p><p><strong>Lock</strong></p><p>A lock can be used for exclusive access to a resource. Once a thread acquires a lock, no other threads can acquire it (and proceed further) unless the lock is released.</p><p><strong>RLock</strong></p><p>RLock is a re-entrant lock. It allows when a holding thread requests the lock again.</p><p>The simple lock is not aware of the current locking thread and this can lead to deadlocks.</p><pre>import threading<br>num = 0<br>lock = Threading.Lock()<br>lock.acquire()<br>num += 1<br>lock.acquire() # This will block. The program goes into a deadlock after this.<br>num += 2<br>lock.release()</pre><pre># With RLock, that problem doesn&#39;t happen.<br>lock = Threading.RLock()<br><br>lock.acquire()<br>num += 3<br>lock.acquire() # This won&#39;t block.<br>num += 4<br>lock.release()<br>lock.release() # We need to call release once for each call to acquire</pre><p>For brevity, let’s skip the other primitives (Semaphore &amp; Barrier, Events &amp; Conditions).</p><p>Lock acquisition and release can be managed using context managers.</p><pre>lock = Threading.Lock()<br>lock.acquire()<br>num += 1<br>lock.release()</pre><p>is equivalent to:</p><pre>lock = Threading.Lock()<br>with lock:<br>    num += 1</pre><h3>Thread safe counter implementation</h3><p>We can use a lock at places of code where race conditions(simultaneous modifications in this case) should be avoided.</p><pre>import concurrent.futures<br>import dis<br>import time<br>from threading import Lock<br><br>count = 0<br>lock = Lock()<br><br>def increase_counter():<br>    global count<br>    for i in range(1000):<br>        lock.acquire()<br>        count += 1<br>        lock.release()<br>        &quot;&quot;&quot;<br>        or:<br>        with lock:<br>        count += 1<br>        &quot;&quot;&quot;<br><br>with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:<br>    for _ in range(10_000):<br>        executor.submit(increase_counter)<br><br>print(F&quot;{count=}&quot;) # count=10000000, for all executions</pre><h3>Thread-safe singleton implementation</h3><pre>class Singleton:<br>  _instance = None<br>  _lock = threading.Lock()<br><br>def __new__(cls):<br>      if cls._instance is None:<br>        with cls._lock:<br>          if cls._instance is None:<br>              cls._instance = super().__new__(cls)<br>          <br>    return cls._instance</pre><p>After acquiring the lock (using with), we are rechecking the presence of an instance to prevent the below-race condition.</p><p>Consider two threads thread1 and thread2.</p><p>1. Both execute `new` dunder of singleton class at the same time.</p><p>2. cls_.instance is currently None, so both thread tries to acquire the lock</p><p>3. thread1 gets the lock while thread2 is blocked waiting.</p><p>4. thread1 creates the singleton instance and completes execution inside the context manager. Once it exits the with block, the lock (cls._lock`) is released.</p><p>5. Now, thread2 is unblocked and enters the context manager body by acquiring the lock. Since the None check for cls._instance fails, thread2 leaves execution and the already existing instance is returned.</p><h3>Thread safe print implementation</h3><p>Similar to the previous examples, we can use a lock here.</p><pre>from concurrent import futures<br>from threading import Lock<br><br>lock = Lock()<br>def printer():<br>    with lock:<br>        print(&#39;testing thread safety of print&#39;)<br><br>with futures.ThreadPoolExecutor(max_workers=10) as executor:<br>    for _ in range(100):<br>        executor.submit(printer)</pre><h3>Context switching &amp; Thread switch interval</h3><p>The switch interval in Python specifies how long the Python interpreter will allow a Python thread to run, after which it is forced for a context switch.</p><p>Since only one thread runs at a time due to GIL, the interpreter tries to switch threads after this interval.</p><p>The default interval is 5 milliseconds.</p><pre>&gt;&gt;&gt; import sys<br>&gt;&gt;&gt; sys.getswitchinterval()<br>0.005</pre><p>We can set custom thread switch interval using sys.setswitchinterval (<a href="https://docs.python.org/3/library/sys.html#sys.setswitchinterval">https://docs.python.org/3/library/sys.html#sys.setswitchinterval</a>)</p><p>If the threads are waiting (e.g.: for IO operations) this switching allows for a parallel execution-like effect. If threads are running any CPU-bound operations, this context switch causes a performance penalty.</p><p>Eg: Network IO blocked tasks:</p><pre>import time<br>import requests<br>start = time.perf_counter()<br>req1 = requests.get(&quot;https://reqres.in/api/users?delay=3&quot;)<br>req2 = requests.get(&quot;https://reqres.in/api/users?delay=3&quot;)<br>end = time.perf_counter()<br>print(end-start, &quot; seconds&quot;) # 6.9710999 seconds</pre><p>Using threads:</p><pre>import threading<br>import time<br>import requests<br><br>def make_request():<br>    return requests.get(&quot;https://reqres.in/api/users?delay=3&quot;)<br><br>start = time.perf_counter()<br>t1 = threading.Thread(target=make_request)<br>t2 = threading.Thread(target=make_request)<br>t1.start()<br>t2.start()<br>t1.join()<br>t2.join()<br>end = time.perf_counter()<br>print(end-start, &quot; seconds&quot;) # 3.494618 seconds</pre><p>In case of<strong> CPU Blocked tasks</strong>:</p><pre>import time<br>start = time.perf_counter()<br>s1 = sum(range(100000000))<br>s2 = sum(range(100000000))<br>end = time.perf_counter()<br>print(end-start, &quot; seconds&quot;) # 3.8891145 seconds</pre><p>Using threads:</p><pre>import threading<br>import time<br>import requestsdef make_request(): <br>    return sum(range(100000000))<br>start = time.perf_counter()<br>t1 = threading.Thread(target=make_request)<br>t2 = threading.Thread(target=make_request)<br>t1.start()<br>t2.start()<br>t1.join()<br>t2.join()<br>end = time.perf_counter()<br>print(end-start, &quot; seconds&quot;) # 3.9622078999999997 seconds</pre><p>As expected, the use of threading slowed down this CPU-bound operation.</p><h3>Revisiting the increment_counter example</h3><p>On running the non-thread-safe increment_counter() used above using Python 3.11 always gives the expected result and race conditions are not seen.</p><p>We can use dis module to inspect the Python bytecode for the increase_counter function</p><pre>import dis<br>count = 0<br>def increase_counter():<br>    global count<br>    for i in range(1000):<br>        count += 1<br>dis.dis(increase_counter)</pre><p>Python 3.9 output:</p><pre>9 0 LOAD_GLOBAL 0 (range)<br>2 LOAD_CONST 1 (1000)<br>4 CALL_FUNCTION 1<br>6 GET_ITER<br>&gt;&gt; 8 FOR_ITER 12 (to 22)<br>10 STORE_FAST 0 (i)10 12 LOAD_GLOBAL 1 (count)<br>14 LOAD_CONST 2 (1)<br>16 INPLACE_ADD<br>18 STORE_GLOBAL 1 (count)<br>20 JUMP_ABSOLUTE 8<br>&gt;&gt; 22 LOAD_CONST 0 (None)<br>24 RETURN_VALUE</pre><p>Python 3.11 output:</p><pre>7 0 RESUME 09 2 LOAD_GLOBAL 1 (NULL + range)<br>14 LOAD_CONST 1 (1000)<br>16 PRECALL 1<br>20 CALL 1<br>30 GET_ITER<br>&gt;&gt; 32 FOR_ITER 12 (to 58)<br>34 STORE_FAST 0 (i)10 36 LOAD_GLOBAL 2 (count)<br>48 LOAD_CONST 2 (1)<br>50 BINARY_OP 13 (+=)<br>54 STORE_GLOBAL 1 (count)<br>56 JUMP_BACKWARD 13 (to 32)9 &gt;&gt; 58 LOAD_CONST 0 (None)<br>60 RETURN_VALUE</pre><p>We can see that INPLACE_ADD opcode has been replaced with BINARY_OP in Python 3.11. I guess that the BINARY_OP is now a thread-safe operation.</p><h3>References</h3><ul><li>Medium article by Jordan Gillard: <a href="https://medium.com/analytics-vidhya/how-to-create-a-thread-safe-singleton-class-in-python-822e1170a7f6">https://medium.com/analytics-vidhya/how-to-create-a-thread-safe-singleton-class-in-python-822e1170a7f6</a></li><li>RealPython Article on Threading: <a href="https://realpython.com/intro-to-python-threading/#working-with-many-threads">https://realpython.com/intro-to-python-threading/#working-with-many-threads</a></li><li>Article by Saurabh Chaturvedi: <a href="https://betterprogramming.pub/synchronization-primitives-in-python-564f89fee732">https://betterprogramming.pub/synchronization-primitives-in-python-564f89fee732</a></li><li>Superfastpython — Thread Safe print: <a href="https://superfastpython.com/thread-safe-print-in-python/">https://superfastpython.com/thread-safe-print-in-python/</a></li></ul><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7441f8627d46" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/thread-safety-in-python-7441f8627d46">Thread Safety in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>