Real Python2024-03-27T14:00:00+00:00https://realpython.com/Real PythonReading and Writing WAV Files in Pythonhttps://realpython.com/python-wav-files/2024-03-27T14:00:00+00:00In this tutorial, you'll learn how to work with WAV audio files in Python using the standard-library wave module. Along the way, you'll synthesize sounds from scratch, visualize waveforms in the time domain, animate real-time spectrograms, and apply special effects to widen the stereo field.
<div><p>There’s an abundance of third-party tools and libraries for manipulating and analyzing audio WAV files in Python. At the same time, the language ships with the little-known <code>wave</code> module in its standard library, offering a quick and straightforward way to read and write such files. Knowing Python’s <code>wave</code> module can help you dip your toes into digital audio processing.</p>
<p>If topics like audio analysis, sound editing, or music synthesis get you excited, then you’re in for a treat, as you’re about to get a taste of them!</p>
<p><strong>In this tutorial, you’ll learn how to:</strong></p>
<ul>
<li><strong>Read</strong> and <strong>write</strong> WAV files using pure Python</li>
<li>Handle the 24-bit <strong>PCM encoding</strong> of audio samples</li>
<li><strong>Interpret</strong> and <strong>plot</strong> the underlying <strong>amplitude levels</strong></li>
<li>Record <strong>online audio streams</strong> like Internet radio stations</li>
<li>Animate <strong>visualizations</strong> in the <strong>time</strong> and <strong>frequency</strong> domains</li>
<li><strong>Synthesize</strong> sounds and apply <strong>special effects</strong></li>
</ul>
<p>Although not required, you’ll get the most out of this tutorial if you’re familiar with <a href="https://realpython.com/numpy-tutorial/">NumPy</a> and <a href="https://realpython.com/python-matplotlib-guide/">Matplotlib</a>, which greatly simplify working with audio data. Additionally, knowing about <a href="https://realpython.com/python-array/">numeric arrays</a> in Python will help you better understand the underlying data representation in computer memory.</p>
<p>Click the link below to access the bonus materials, where you’ll find <strong>sample audio files</strong> for practice, as well as the <strong>complete source code</strong> of all the examples demonstrated in this tutorial:</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/python-wav-files-code/" class="alert-link" data-toggle="modal" data-target="#modal-python-wav-files-code" data-focus="false" markdown="1">Click here to download the free sample code</a> that shows you how to read and write WAV files in Python.</p>
</div>
<p>You can also take the quiz to test your knowledge and see how much you’ve learned:</p>
<div class="alert alert-primary" role="alert">
<p><strong><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@quiz"></use></svg></span> Take the Quiz:</strong> Test your knowledge with our interactive “Reading and Writing WAV Files in Python” quiz. Upon completion you will receive a score so you can track your learning progress over time:</p>
<p class="text-center my-2"><a class="btn btn-primary" href="/quizzes/python-wav-files/" target="_blank">Take the Quiz »</a></p>
</div>
<h2 id="understand-the-wav-file-format">Understand the WAV File Format<a class="headerlink" href="#understand-the-wav-file-format" title="Permanent link"></a></h2>
<p>In the early nineties, Microsoft and IBM jointly developed the <a href="https://en.wikipedia.org/wiki/WAV">Waveform Audio File Format</a>, often abbreviated as WAVE or WAV, which stems from the file’s extension (<code>.wav</code>). Despite its older age in computer terms, the format remains relevant today. There are several good reasons for its wide adoption, including:</p>
<ul>
<li><strong>Simplicity:</strong> The WAV file format has a straightforward structure, making it relatively uncomplicated to decode in software and understand by humans.</li>
<li><strong>Portability:</strong> Many software systems and hardware platforms support the WAV file format as standard, making it suitable for data exchange.</li>
<li><strong>High Fidelity:</strong> Because most WAV files contain raw, uncompressed audio data, they’re perfect for applications that require the highest possible sound quality, such as with music production or audio editing. On the flipside, WAV files take up significant storage space compared to <a href="https://en.wikipedia.org/wiki/Lossy_compression">lossy compression</a> formats like MP3.</li>
</ul>
<p>It’s worth noting that WAV files are specialized kinds of the <a href="https://en.wikipedia.org/wiki/Resource_Interchange_File_Format">Resource Interchange File Format (RIFF)</a>, which is a container format for audio and video streams. Other popular file formats based on RIFF include <a href="https://en.wikipedia.org/wiki/Audio_Video_Interleave">AVI</a> and <a href="https://en.wikipedia.org/wiki/MIDI">MIDI</a>. RIFF itself is an extension of an even older <a href="https://en.wikipedia.org/wiki/Interchange_File_Format">IFF</a> format originally developed by Electronic Arts to store video game resources.</p>
<p>Before diving in, you’ll deconstruct the WAV file format itself to better understand its structure and how it represents sounds. Feel free to jump ahead if you just want to see <a href="#get-to-know-pythons-wave-module">how to use the <code>wave</code> module</a> in Python.</p>
<h3 id="the-waveform-part-of-wav">The Waveform Part of WAV<a class="headerlink" href="#the-waveform-part-of-wav" title="Permanent link"></a></h3>
<p>What you perceive as sound is a disturbance of pressure traveling through a physical medium, such as air or water. At the most fundamental level, every sound is a <a href="https://en.wikipedia.org/wiki/Wave">wave</a> that you can describe using three attributes:</p>
<ol>
<li><a href="https://en.wikipedia.org/wiki/Amplitude">Amplitude</a> is the measure of the sound wave’s strength, which you perceive as <a href="https://en.wikipedia.org/wiki/Loudness">loudness</a>.</li>
<li><a href="https://en.wikipedia.org/wiki/Frequency">Frequency</a> is the reciprocal of the <a href="https://en.wikipedia.org/wiki/Wavelength">wavelength</a> or the number of oscillations per second, which corresponds to the <a href="https://en.wikipedia.org/wiki/Pitch_(music)">pitch</a>.</li>
<li><a href="https://en.wikipedia.org/wiki/Phase_(waves)">Phase</a> is the point in the wave cycle at which the wave starts, not registered by the human ear directly.</li>
</ol>
<p>The word <a href="https://en.wikipedia.org/wiki/Waveform">waveform</a>, which appears in the WAV file format’s name, refers to the graphical depiction of the audio signal’s shape. If you’ve ever opened a sound file using audio editing software, such as <a href="https://www.audacityteam.org/">Audacity</a>, then you’ve likely seen a visualization of the file’s content that looked something like this:</p>
<figure class="js-lightbox"><a href="https://files.realpython.com/media/audacity_waveform.d53954eea4a1.png" target="_blank"><img loading="lazy" class="img-fluid mx-auto d-block border " src="https://files.realpython.com/media/audacity_waveform.d53954eea4a1.png" width="1920" height="1080" srcset="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/audacity_waveform.d53954eea4a1.png&w=480&sig=f20342eda88604314aaa42a0a1a6eea807c35468 480w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/audacity_waveform.d53954eea4a1.png&w=640&sig=fe1b03504ee9f5c2f845be1f3a307d9096d26861 640w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/audacity_waveform.d53954eea4a1.png&w=960&sig=a638b8475db99b6843d6449a01471c0efd7cc5b8 960w, https://files.realpython.com/media/audacity_waveform.d53954eea4a1.png 1920w" sizes="(min-width: 1200px) 690px, (min-width: 780px) calc(-5vw + 669px), (min-width: 580px) 510px, calc(100vw - 30px)" alt="Waveform in Audacity" data-asset="5691"></a><figcaption class="figure-caption text-center">Waveform in Audacity</figcaption></figure>
<p>That’s your audio waveform, illustrating how the amplitude changes over time.</p>
<p>The vertical axis represents the <strong>amplitude</strong> at any given point in time. The midpoint of the graph, which is a horizontal line passing through the center, represents the baseline amplitude or the point of silence. Any deviation from this equilibrium corresponds to a higher positive or negative amplitude, which you experience as a louder sound.</p>
<p>As you move from left to right along the graph’s horizontal scale, which is the <strong>timeline</strong>, you’re essentially moving forward in time through your audio track.</p>
<p>Having such a view can help you visually inspect the characteristics of your audio file. The series of the amplitude’s peaks and valleys reflect the volume changes. Therefore, you can leverage the waveform to identify parts where certain sounds occur or find quiet sections that may need editing.</p>
<p>Coming up next, you’ll learn how WAV files store these amplitude levels in digital form.</p>
<h3 id="the-structure-of-a-wav-file">The Structure of a WAV File<a class="headerlink" href="#the-structure-of-a-wav-file" title="Permanent link"></a></h3>
</div><h2><a href="https://realpython.com/python-wav-files/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/python-wav-files/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Finding Python Easter Eggshttps://realpython.com/courses/finding-python-easter-eggs/2024-03-26T14:00:00+00:00Python has its fair share of hidden surprises, commonly known as Easter eggs. From clever jokes to secret messages, these little mysteries are often meant to be discovered by curious geeks like you!
<p>In this <strong>Code Conversation</strong>, you’ll follow a chat between Philipp and Bartosz as they go on an Easter egg hunt. Along the way, you’ll:</p>
<ul>
<li>Learn about Easter egg hunt traditions</li>
<li>Uncover the first Easter egg in software</li>
<li>Explore Easter eggs in Python</li>
</ul>
<p>There won’t be many code examples in this Code Conversation, so you can lean back and join Philipp and Bartosz on their Easter egg hunt.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Prompt Engineering: A Practical Examplehttps://realpython.com/practical-prompt-engineering/2024-03-25T14:00:00+00:00Learn prompt engineering techniques with a practical, real-world project to get better results from large language models. This tutorial covers zero-shot and few-shot prompting, delimiters, numbered steps, role prompts, chain-of-thought prompting, and more. Improve your LLM-assisted projects today.
<div><p>You’ve used <a href="https://realpython.com/chatgpt-coding-mentor-python/">ChatGPT</a>, and you understand the potential of using a <strong>large language model (LLM)</strong> to assist you in your tasks. Maybe you’re already working on an LLM-supported application and have read about <strong>prompt engineering</strong>, but you’re unsure how to translate the theoretical concepts into a practical example.</p>
<p>Your text prompt instructs the LLM’s responses, so tweaking it can get you vastly different output. In this tutorial, you’ll apply multiple <strong>prompt engineering techniques</strong> to a real-world example. You’ll experience prompt engineering as an iterative process, see the effects of applying various techniques, and learn about related concepts from machine learning and data engineering.</p>
<p><strong>In this tutorial, you’ll learn how to:</strong></p>
<ul>
<li>Work with OpenAI’s <strong>GPT-3.5</strong> and <strong>GPT-4</strong> models through their <strong>API</strong></li>
<li>Apply prompt engineering techniques to a <strong>practical, real-world example</strong></li>
<li>Use <strong>numbered steps</strong>, <strong>delimiters</strong>, and <strong>few-shot prompting</strong> to improve your results</li>
<li>Understand and use <strong>chain-of-thought prompting</strong> to add more context</li>
<li>Tap into the power of <strong>roles</strong> in messages to go beyond using singular <strong>role prompts</strong></li>
</ul>
<p>You’ll work with a <strong>Python script</strong> that you can repurpose to fit your own LLM-assisted task. So if you’d like to use practical examples to discover how you can use prompt engineering to get better results from an LLM, then you’ve found the right tutorial!</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/prompt-engineering-code/" class="alert-link" data-toggle="modal" data-target="#modal-prompt-engineering-code" data-focus="false" markdown="1">Click here to download the sample code </a> that you’ll use to get the most out of large language models through prompt engineering.</p>
</div>
<div class="alert alert-primary" role="alert">
<p><strong><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@quiz"></use></svg></span> Take the Quiz:</strong> Test your knowledge with our interactive “Practical Prompt Engineering” quiz. Upon completion you will receive a score so you can track your learning progress over time:</p>
<p class="text-center my-2"><a class="btn btn-primary" href="/quizzes/practical-prompt-engineering/" target="_blank">Take the Quiz »</a></p>
</div>
<h2 id="understand-the-purpose-of-prompt-engineering">Understand the Purpose of Prompt Engineering<a class="headerlink" href="#understand-the-purpose-of-prompt-engineering" title="Permanent link"></a></h2>
<p>Prompt engineering is more than a buzzword. You can get vastly different output from an LLM when using different prompts. That may seem obvious when you consider that you get different output when you ask different questions—but it also applies to phrasing the same conceptual question differently. Prompt engineering means constructing your text input to the LLM using specific approaches.</p>
<p>You can think of prompts as arguments and the LLM as the function to which you pass these arguments. Different input means different output:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="pycon" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">>>> </span><span class="k">def</span> <span class="nf">hello</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Hello, </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s2">!"</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">hello</span><span class="p">(</span><span class="s2">"World"</span><span class="p">)</span>
<span class="go">Hello, World!</span>
<span class="gp">>>> </span><span class="n">hello</span><span class="p">(</span><span class="s2">"Engineer"</span><span class="p">)</span>
<span class="go">Hello, Engineer!</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>While an LLM is much more complex than the toy function above, the fundamental idea holds true. For a successful function call, you’ll need to know exactly which argument will produce the desired output. In the case of an LLM, that argument is text that consists of many different <strong>tokens</strong>, or <a href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them">pieces of words</a>.</p>
<div class="alert alert-primary" role="alert">
<p><strong>Note:</strong> The analogy of a function and its arguments has a caveat when dealing with OpenAI’s LLMs. While the <code>hello()</code> function above will always return the same result given the same input, the results of your LLM interactions won’t be 100 percent deterministic. This is currently inherent to how these models operate.</p>
</div>
<p>The field of prompt engineering is still changing rapidly, and there’s a lot of active research happening in this area. As LLMs continue to evolve, so will the prompting approaches that will help you achieve the best results.</p>
<p>In this tutorial, you’ll cover some prompt engineering techniques, along with approaches to iteratively developing prompts, that you can use to get better text completions for your own LLM-assisted projects:</p>
<ul>
<li><a href="#describe-your-task">Zero-Shot Prompting</a></li>
<li><a href="#use-few-shot-prompting-to-improve-output">Few-Shot Prompting</a></li>
<li><a href="#use-delimiters-to-clearly-mark-sections-of-your-prompt">Delimiters</a></li>
<li><a href="#describe-your-request-in-numbered-steps">Numbered Steps</a></li>
<li><a href="#add-a-role-prompt-to-set-the-tone">Role Prompts</a></li>
<li><a href="#walk-the-model-through-chain-of-thought-prompting">Chain-of-Thought (CoT) Prompting</a></li>
<li><a href="#structure-your-output-format-as-json">Structured Output</a></li>
<li><a href="#improve-your-output-with-the-power-of-conversation">Labeled Conversations</a></li>
</ul>
<p>There are more techniques to uncover, and you’ll also find links to additional resources in the tutorial. Applying the mentioned techniques in a practical example will give you a great starting point for improving your LLM-supported programs. If you’ve never worked with an LLM before, then you may want to peruse <a href="https://platform.openai.com/docs/guides/gpt">OpenAI’s GPT documentation</a> before diving in, but you should be able to follow along either way.</p>
<h2 id="get-to-know-the-practical-prompt-engineering-project">Get to Know the Practical Prompt Engineering Project<a class="headerlink" href="#get-to-know-the-practical-prompt-engineering-project" title="Permanent link"></a></h2>
<p>You’ll explore various prompt engineering techniques in service of a practical example: <a href="https://en.wikipedia.org/wiki/Data_sanitization">sanitizing</a> customer chat conversations. By practicing different prompt engineering techniques on a single real-world project, you’ll get a good idea of why you might want to use one technique over another and how you can apply them in practice.</p>
<p>Imagine that you’re the resident Python developer at a company that handles thousands of customer support chats on a daily basis. Your job is to format and sanitize these conversations. You also help with deciding which of them require additional attention.</p>
<h3 id="collect-your-tasks">Collect Your Tasks<a class="headerlink" href="#collect-your-tasks" title="Permanent link"></a></h3>
<p>Your big-picture assignment is to help your company stay on top of handling customer chat conversations. The conversations that you work with may look like the one shown below:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="text">
<div class="codeblock__header d-flex justify-content-between codeblock--grey">
<span class="mr-2 noselect" aria-label="Language">Text</span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code>[support_tom] 2023-07-24T10:02:23+00:00 : What can I help you with?
[johndoe] 2023-07-24T10:03:15+00:00 : I CAN'T CONNECT TO MY BLASTED ACCOUNT
[support_tom] 2023-07-24T10:03:30+00:00 : Are you sure it's not your caps lock?
[johndoe] 2023-07-24T10:04:03+00:00 : Blast! You're right!
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>You’re supposed to make these text conversations more accessible for further processing by the customer support department in a few different ways:</p>
<blockquote>
<ul>
<li>Remove personally identifiable information.</li>
<li>Remove swear words.</li>
<li>Clean the date-time information to only show the date.</li>
</ul>
</blockquote>
</div><h2><a href="https://realpython.com/practical-prompt-engineering/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/practical-prompt-engineering/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #197: Using Python in Bioinformatics and the Laboratoryhttps://realpython.com/podcasts/rpp/197/2024-03-22T12:00:00+00:00How is Python being used to automate processes in the laboratory? How can it speed up scientific work with DNA sequencing? This week on the show, Chemical Engineering PhD Student Parsa Ghadermazi is here to discuss Python in bioinformatics.
<p>How is Python being used to automate processes in the laboratory? How can it speed up scientific work with DNA sequencing? This week on the show, Chemical Engineering PhD Student Parsa Ghadermazi is here to discuss Python in bioinformatics.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Build a Python Turtle Game: Space Invaders Clonehttps://realpython.com/build-python-turtle-game-space-invaders-clone/2024-03-20T14:00:00+00:00In this step-by-step tutorial, you'll use Python's turtle module to write a Space Invaders clone. You'll learn about techniques used in animations and games, and consolidate your knowledge of key Python topics.
<div><p>In this tutorial, you’ll use Python’s <code>turtle</code> module to build a Space Invaders clone. The game <a href="https://en.wikipedia.org/wiki/Space_Invaders">Space Invaders</a> doesn’t need any introduction. The original game was released in 1978 and is one of the most recognized video games of all time. It undeniably defined its own video game genre. In this tutorial, you’ll create a basic clone of this game.</p>
<p>The <code>turtle</code> module you’ll use to build the game is part of Python’s standard library, and it enables you to draw and move sprites on the screen. The <code>turtle</code> module is not a game-development package, but it gives instructions about creating a <em><code>turtle</code> game</em>, which will help you understand how video games are built.</p>
<p><strong>In this tutorial, you’ll learn how to:</strong></p>
<ul>
<li><strong>Design and build</strong> a classic video game</li>
<li>Use the <code>turtle</code> module to <strong>create animated sprites</strong></li>
<li>Add <strong>user interaction</strong> in a graphics-based program</li>
<li><strong>Create a game loop</strong> to control each frame of the game</li>
<li><strong>Use functions</strong> to represent key actions in the game</li>
</ul>
<p>This tutorial is ideal for anyone who is familiar with the core Python topics and wants to use them to build a classic video game from scratch. You don’t need to be familiar with the <code>turtle</code> module to work through this tutorial. You can download the code for each step by clicking on the link below:</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/build-python-turtle-game-space-invaders-clone-code/" class="alert-link" data-toggle="modal" data-target="#modal-build-python-turtle-game-space-invaders-clone-code" data-focus="false" markdown="1">Click here to download the free sample code</a> that shows you how to build a Python turtle game.</p>
</div>
<p>In the next section, you can have a look at the version of the game you’ll build as you follow the steps outlined in this tutorial.</p>
<h2 id="demo-a-python-turtle-space-invaders-game">Demo: A Python Turtle Space Invaders Game<a class="headerlink" href="#demo-a-python-turtle-space-invaders-game" title="Permanent link"></a></h2>
<p>You’ll build a simplified version of the classic Space Invaders game and control the laser cannon with the keys on your keyboard. You’ll shoot lasers from the cannon by pressing the spacebar, and aliens will appear at regular intervals at the top of the screen and move downwards. Your task is to shoot the aliens before they reach the bottom of the screen. The game ends when one alien reaches the bottom.</p>
<p>This is what your <code>turtle</code> game will look like when you complete this tutorial:</p>
<figure>
<div class="embed-responsive embed-responsive-16by9 rounded mb-3 ">
<iframe loading="lazy" class="embed-responsive-item" src="https://player.vimeo.com/video/920307157?background=1" frameborder="0" allow="fullscreen" allowfullscreen></iframe>
</div>
</figure>
<p>Here you can see the main game play for this game, as the laser cannon moves back and forth and shoots the falling aliens. The game also displays the elapsed time and the number of aliens shot down on the screen.</p>
<h2 id="project-overview">Project Overview<a class="headerlink" href="#project-overview" title="Permanent link"></a></h2>
<p>In this project, you’ll start by creating the screen that will contain the game. In each step, you’ll create game components such as the laser cannon, lasers, and aliens, and you’ll add the features required to make a functioning game.</p>
<p>To create this <code>turtle</code> game, you’ll work through the following steps:</p>
<ol>
<li>Create the game <strong>screen</strong> and the <strong>laser cannon</strong></li>
<li><strong>Move the cannon</strong> left and right using keys</li>
<li><strong>Shoot lasers</strong> with the spacebar</li>
<li><strong>Create aliens</strong> and move them towards the bottom of the screen</li>
<li>Determine when <strong>a laser hits an alien</strong></li>
<li><strong>End the game</strong> when an alien reaches the bottom</li>
<li>Add a <strong>timer</strong> and a <strong>score</strong></li>
<li><strong>Improve the cannon’s movement</strong> to make the game smoother</li>
<li>Set the game’s <strong>frame rate</strong></li>
</ol>
<p>You’ll start with a blank screen, and then see the game come to life one feature at a time as you work through each step in this tutorial.</p>
<h2 id="prerequisites">Prerequisites<a class="headerlink" href="#prerequisites" title="Permanent link"></a></h2>
<p>To complete this tutorial, you should be comfortable with the following concepts:</p>
<ul>
<li>Repeating code using <a href="https://realpython.com/python-for-loop/"><code>for</code> loops</a> and <a href="https://realpython.com/python-for-loop/"><code>while</code> loops</a></li>
<li>Using <a href="https://realpython.com/python-conditional-statements/"><code>if</code> statements</a> to control what happens in different conditions</li>
<li><a href="https://realpython.com/defining-your-own-python-function/">Defining functions</a> to encapsulate code</li>
<li>Using <a href="https://realpython.com/python-lists-tuples/">lists</a> to store multiple items</li>
</ul>
<p>You don’t need to be familiar with Python’s <code>turtle</code> to start this tutorial. However, you can <a href="https://realpython.com/beginners-guide-python-turtle/">read an overview of the <code>turtle</code> module</a> to find out more about the basics.</p>
<p>If you don’t have all of the prerequisite knowledge before you start, that’s okay! In fact, you might learn more by going ahead and getting started! You can always stop and review the resources linked here if you get stuck.</p>
<h2 id="step-1-set-up-the-turtle-game-with-a-screen-and-a-laser-cannon">Step 1: Set Up the Turtle Game With a Screen and a Laser Cannon<a class="headerlink" href="#step-1-set-up-the-turtle-game-with-a-screen-and-a-laser-cannon" title="Permanent link"></a></h2>
<p>You can’t have a game without a screen where all the action happens. So, the first step is to create a blank screen. Then, you can add sprites to represent the items in the game. In this project, you can run your code at any point to see the game in its current state.</p>
<p>You can download the code as it’ll look at the end of this step from the folder named <code>source_code_step_1/</code> in the link below:</p>
</div><h2><a href="https://realpython.com/build-python-turtle-game-space-invaders-clone/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/build-python-turtle-game-space-invaders-clone/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
SQLite and SQLAlchemy in Python: Move Your Data Beyond Flat Fileshttps://realpython.com/courses/sqlite-sqlalchemy-python-beyond-flat-files/2024-03-19T14:00:00+00:00In this video course, you'll learn how to store and retrieve data using Python, SQLite, and SQLAlchemy as well as with flat files. Using SQLite with Python brings with it the additional benefit of accessing data with SQL. By adding SQLAlchemy, you can work with data in terms of objects and methods.
<p>All programs process data in one form or another, and many need to be able to save and retrieve that data from one invocation to the next. Python, <a href="https://www.sqlite.org/index.html">SQLite</a>, and <a href="https://www.sqlalchemy.org/">SQLAlchemy</a> give your programs database functionality, allowing you to store data in a single file without the need for a database server.</p>
<p>You can achieve similar results using <a href="https://en.wikipedia.org/wiki/Flat-file_database">flat files</a> in any number of formats, including CSV, JSON, XML, and even custom formats. Flat files are often human-readable text files—though they can also be binary data—with a structure that can be parsed by a computer program. You’ll explore using SQL databases and flat files for data storage and manipulation and learn how to decide which approach is right for your program.</p>
<p><strong>In this video course, you’ll learn how to use:</strong></p>
<ul>
<li><strong>Flat files</strong> for data storage</li>
<li><strong>SQL</strong> to improve access to persistent data</li>
<li><strong>SQLite</strong> for data storage</li>
<li><strong>SQLAlchemy</strong> to work with data as Python objects</li>
</ul>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Model-View-Controller (MVC) in Python Web Apps: Explained With Legohttps://realpython.com/lego-model-view-controller-python/2024-03-18T14:00:00+00:00This tutorial conceptually explains the Model-View-Controller (MVC) pattern in Python web apps using Lego bricks. Finally understand this important architecture to streamline your web development process.
<div><p>If you’re curious about web development, then you’ve likely encountered the abbreviation <strong>MVC</strong>, which stands for <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">Model-View-Controller</a>. You may know that it’s a common design pattern that’s fundamental to many Python web frameworks and even desktop applications.</p>
<p>But what exactly does it mean? If you’ve had a hard time wrapping your head around the concept, then keep on reading.</p>
<p><strong>In this tutorial, you’ll:</strong></p>
<ul>
<li>Approach <strong>understanding the MVC pattern</strong> through a <strong>Lego</strong>-based analogy</li>
<li>Learn what models, views, and controllers are <strong>conceptually</strong></li>
<li>Tie your conceptual understanding back to <strong>concrete web development examples</strong></li>
<li>Investigate <strong>Flask code snippets</strong> to drive the point home </li>
</ul>
<p>Maybe you built things with Lego as a kid, or maybe you’re still a Lego-aficionado today. But even if you’ve never pieced two Lego blocks together, keep on reading because the analogy might still be a good building block for your understanding.</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/the-model-view-controller-mvc-paradigm-summarized-with-lego-update-code/" class="alert-link" data-toggle="modal" data-target="#modal-the-model-view-controller-mvc-paradigm-summarized-with-lego-update-code" data-focus="false" markdown="1">Click here to download an example Flask app </a> that will help you understand MVC in Python web apps.</p>
</div>
<div class="alert alert-primary" role="alert">
<p><strong><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@quiz"></use></svg></span> Take the Quiz:</strong> Test your knowledge with our interactive “Model-View-Controller (MVC) in Python Web Apps: Explained With Lego” quiz. Upon completion you will receive a score so you can track your learning progress over time:</p>
<p class="text-center my-2"><a class="btn btn-primary" href="/quizzes/model-view-controller-mvc-python-web-apps-lego/" target="_blank">Take the Quiz »</a></p>
</div>
<h2 id="explaining-the-model-view-controller-pattern-with-lego">Explaining the Model-View-Controller Pattern With Lego<a class="headerlink" href="#explaining-the-model-view-controller-pattern-with-lego" title="Permanent link"></a></h2>
<p>Imagine that you’re ten years old and sitting on your family room floor. In front of you is a big bucket of <a href="https://en.wikipedia.org/wiki/Lego">Lego</a>, or similar <a href="https://en.wikipedia.org/wiki/Building_blocks_(toy)">modular building blocks</a>. There are blocks of all different shapes and sizes:</p>
<ul>
<li>🟦🟦🟦 Some are blue, tall, and long.</li>
<li>🟥 Some are red and cube-shaped.</li>
<li>🟨🟨 Some are yellow, big, and wide.</li>
</ul>
<p>With all of these different Lego pieces, there’s no telling what you could build!</p>
<p>Just as your mind is filling with the endless possibilities, you hear something coming from the direction of the couch. It’s your older brother, voicing a specific <strong>request</strong>. He’s saying, <em>“Hey! Build me a spaceship!”</em></p>
<p><em>“Alright,”</em> you think, <em>“that could actually be pretty cool.”</em> A spaceship it is!</p>
<p>So you get to work. You start pulling out the Lego blocks that you think you’re going to need. Some big, some small. Different colors for the outside of the spaceship, different colors for the engines.</p>
<p>Now that you have all of your <strong>building blocks</strong> in place, it’s time to assemble the spaceship. And after a few hours of hard work, you now have in front of you—a spaceship:</p>
<div class="highlight"><pre><span></span><code> 🟦
🟦🟥🟦
🟦🟥🟥🟥🟦
🟦🟥🟥🟥🟥🟥🟦
🟦🟥🟥🟥🟥🟥🟦
🟦🟥🟩🟩🟩🟥🟦
🟦🟥🟩🟦🟩🟥🟦
🟦🟥🟩🟩🟩🟥🟦
🟦🟥🟥🟥🟥🟥🟦
🟦🟥🟥🟥🟥🟥🟦
🟦🟥🟥🟥🟥🟥🟦
🟦🟥🟥🟥🟥🟥🟥🟥🟥🟥🟦
🟦🟥🟥🟥🟥🟥🟥🟥🟥🟥🟦
🟦🟥🟨🟨🟥🟥🟥🟨🟨🟥🟦
🟨🟨 🟨🟨
</code></pre></div>
<p>You run to find your brother and show him the finished product. <em>“Wow, nice work!”</em>, he says. Then he quietly adds:</p>
<blockquote>
<p>Huh, I just asked for that a few hours ago, I didn’t have to do a thing, and here it is. I wish <em>everything</em> was that easy.</p>
<p>— <em>Your Brother</em></p>
</blockquote>
<p>What if I told you that building a web application using the MVC pattern is exactly like building something with Lego blocks?</p>
<h3 id="user-sends-a-request">User Sends a Request<a class="headerlink" href="#user-sends-a-request" title="Permanent link"></a></h3>
</div><h2><a href="https://realpython.com/lego-model-view-controller-python/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/lego-model-view-controller-python/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #196: Exploring Duck Typing in Python & Dynamics of Monkey Patchinghttps://realpython.com/podcasts/rpp/196/2024-03-15T12:00:00+00:00What are the advantages of determining the type of an object by how it behaves? What coding circumstances are not a good fit for duck typing? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.
<p>What are the advantages of determining the type of an object by how it behaves? What coding circumstances are not a good fit for duck typing? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Visualizing Data in Python With Seabornhttps://realpython.com/python-seaborn/2024-03-13T14:00:00+00:00In this tutorial, you'll learn how to use the Python seaborn library to produce statistical data analysis plots to allow you to better visualize your data. You'll learn how to use both its traditional classic interface and more modern objects interface.
<div><p>If you have some experience using Python for <a href="https://realpython.com/python-for-data-analysis/">data analysis</a>, chances are you’ve produced some data plots to explain your analysis to other people. Most likely you’ll have used a library such as <a href="https://realpython.com/python-matplotlib-guide/">Matplotlib</a> to produce these. If you want to take your statistical visualizations to the next level, you should master the <a href="https://seaborn.pydata.org/">Python seaborn library</a> to produce impressive statistical analysis plots that will display your data.</p>
<p><strong>In this tutorial, you’ll learn how to:</strong></p>
<ul>
<li>Make an informed judgment as to whether or not seaborn <strong>meets your data visualization needs</strong></li>
<li>Understand the principles of seaborn’s <strong>classic Python functional interface</strong></li>
<li>Understand the principles of seaborn’s more <strong>contemporary Python objects interface</strong></li>
<li>Create Python plots using seaborn’s <strong>functions</strong></li>
<li>Create Python plots using seaborn’s <strong>objects</strong></li>
</ul>
<p>Before you start, you should familiarize yourself with the <a href="https://realpython.com/jupyter-notebook-introduction/">Jupyter Notebook</a> data analysis tool available in <a href="https://realpython.com/using-jupyterlab/">JupyterLab</a>. Although you can follow along with this seaborn tutorial using your favorite Python environment, Jupyter Notebook is preferred. You might also like to learn how a <a href="https://realpython.com/pandas-dataframe/#introducing-the-pandas-dataframe">pandas DataFrame</a> stores its data. Knowing the difference between a pandas <a href="https://pandas.pydata.org/docs/user_guide/dsintro.html#dataframe">DataFrame</a> and <a href="https://pandas.pydata.org/docs/user_guide/dsintro.html#series">Series</a> will also prove useful.</p>
<p>So now it’s time for you to dive right in and learn how to use seaborn to produce your Python plots.</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Free Bonus:</strong> <a href="https://realpython.com/bonus/python-seaborn-code/" class="alert-link" data-toggle="modal" data-target="#modal-python-seaborn-code" data-focus="false" markdown="1">Click here to download the free code</a> that you can experiment with in Python seaborn.</p>
</div>
<h2 id="getting-started-with-python-seaborn">Getting Started With Python seaborn<a class="headerlink" href="#getting-started-with-python-seaborn" title="Permanent link"></a></h2>
<p>Before you use seaborn, you must install it. Open a Jupyter Notebook and type <code>!python -m pip install seaborn</code> into a new code cell. When you run the cell, seaborn will install. If you’re working at the command line, use the same command, only without the exclamation point (<code>!</code>). Once seaborn is installed, <a href="https://realpython.com/python-matplotlib-guide/">Matplotlib</a>, <a href="https://realpython.com/learning-paths/pandas-data-science/">pandas</a>, and <a href="https://realpython.com/numpy-tutorial/">NumPy</a> will also be available. This is handy because sometimes you need them to enhance your Python seaborn plots.</p>
<p>Before you can create a plot, you do, of course, need data. Later, you’ll create several plots using different publicly available datasets containing real-world data. To begin with, you’ll work with some <a href="https://github.com/mwaskom/seaborn-data">sample data</a> provided for you by the creators of seaborn. More specifically, you’ll work with their <code>tips</code> dataset. This dataset contains data about each tip that a particular restaurant waiter received over a few months.</p>
<h3 id="creating-a-bar-plot-with-seaborn">Creating a Bar Plot With seaborn<a class="headerlink" href="#creating-a-bar-plot-with-seaborn" title="Permanent link"></a></h3>
<p>Suppose you wanted to see a <a href="https://en.wikipedia.org/wiki/Bar_chart">bar plot</a> showing the average amount of tips received by the waiter each day. You could write some Python seaborn code to do this:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="ipython" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">In [1]: </span><span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="hll"><span class="gp"> ...: </span><span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="nn">sns</span>
</span><span class="gp"> ...:</span>
<span class="gp"> ...: </span><span class="n">tips</span> <span class="o">=</span> <span class="n">sns</span><span class="o">.</span><span class="n">load_dataset</span><span class="p">(</span><span class="s2">"tips"</span><span class="p">)</span>
<span class="gp"> ...:</span>
<span class="gp"> ...: </span><span class="p">(</span>
<span class="hll"><span class="gp"> ...: </span> <span class="n">sns</span><span class="o">.</span><span class="n">barplot</span><span class="p">(</span>
</span><span class="hll"><span class="gp"> ...: </span> <span class="n">data</span><span class="o">=</span><span class="n">tips</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="s2">"day"</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="s2">"tip"</span><span class="p">,</span>
</span><span class="hll"><span class="gp"> ...: </span> <span class="n">estimator</span><span class="o">=</span><span class="s2">"mean"</span><span class="p">,</span> <span class="n">errorbar</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
</span><span class="hll"><span class="gp"> ...: </span> <span class="p">)</span>
</span><span class="gp"> ...: </span> <span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">"Daily Tips ($)"</span><span class="p">)</span>
<span class="gp"> ...: </span><span class="p">)</span>
<span class="gp"> ...:</span>
<span class="gp"> ...: </span><span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>First, you import seaborn into your Python code. By convention, you import it as <code>sns</code>. Although you can use any alias you like, <code>sns</code> is a nod to the <a href="https://en.wikipedia.org/wiki/Sam_Seaborn">fictional character</a> the library was named after.</p>
<p>To work with data in seaborn, you usually load it into a pandas DataFrame, although <a href="https://seaborn.pydata.org/tutorial/data_structure.html#data-structures-accepted-by-seaborn">other data structures</a> can also be used. The usual way of loading data is to use the pandas <code>read_csv()</code> function to read data from a file on disk. You’ll see how to do this later.</p>
<p>To begin with, because you’re working with one of the seaborn sample datasets, seaborn allows you online access to these using its <code>load_dataset()</code> function. You can see a list of the freely available files on their <a href="https://github.com/mwaskom/seaborn-data">GitHub repository</a>. To obtain the one you want, all you need to do is pass <code>load_dataset()</code> a string telling it the name of the file containing the dataset you’re interested in, and it’ll be loaded into a pandas DataFrame for you to use.</p>
<p>The actual bar plot is created using seaborn’s <a href="https://seaborn.pydata.org/generated/seaborn.barplot.html#seaborn.barplot"><code>barplot()</code></a> function. You’ll learn more about the different plotting functions later, but for now, you’ve specified <code>data=tips</code> as the DataFrame you wish to use and also told the function to plot the <code>day</code> and <code>tip</code> columns from it. These contain the day the tip was received and the tip amount, respectively.</p>
<p>The important point you should notice here is that the seaborn <code>barplot()</code> function, like all seaborn plotting functions, can understand pandas DataFrames instinctively. To specify a column of data for them to use, you pass its column name as a string. There’s no need to write pandas code to identify each Series to be plotted.</p>
<p>The <code>estimator="mean"</code> parameter tells seaborn to plot the mean <code>y</code> values for each category of <code>x</code>. This means your plot will show the average tip for each day. You can quickly customize this to instead use common statistical functions such as <code>sum</code>, <code>max</code>, <code>min</code>, and <code>median</code>, but <code>estimator="mean"</code> is the default. The plot will also show <a href="https://en.wikipedia.org/wiki/Error_bar">error bars</a> by default. By setting <code>errorbar=None</code>, you can suppress them.</p>
<p>The <code>barplot()</code> function will produce a plot using the parameters you pass to it, and it’ll label each axis using the column name of the data that you want to see. Once <code>barplot()</code> is finished, it returns a matplotlib <a href="https://matplotlib.org/stable/api/axes_api.html"><code>Axes</code></a> object containing the plot. To give the plot a title, you need to call the <code>Axes</code> object’s <code>.set()</code> method and pass it the title you want. Notice that this was all done from within seaborn directly, and not Matplotlib.</p>
<div class="alert alert-primary" role="alert">
<p><strong>Note:</strong> You may be wondering why the <code>barplot()</code> function is encapsulated within a pair of parentheses <code>(...)</code>. This is a coding style often used in seaborn code because it frequently uses <a href="https://en.wikipedia.org/wiki/Method_chaining">method chaining</a>. These extra brackets allow you to horizontally align method calls, starting each with its dot notation. Alternatively, you could use the backslash (<code>\</code>) for line continuation, although that is <a href="https://peps.python.org/pep-0008/#maximum-line-length">discouraged</a>.</p>
<p>If you take another look at the code, the alignment of <code>.set()</code> is only possible because of these extra encasing brackets. You’ll see this coding style used throughout this tutorial, as well as when you read the <a href="https://seaborn.pydata.org/#">seaborn documentation</a>. </p>
</div>
<p>In some environments like <a href="https://realpython.com/ipython-interactive-python-shell/">IPython</a> and <a href="https://realpython.com/pycharm-guide/">PyCharm</a>, you may need to use Matplotlib’s <code>show()</code> function to display your plot, meaning you must import Matplotlib into Python as well. If you’re using a Jupyter notebook, then using <code>plt.show()</code> isn’t necessary, but using it removes some unwanted text above your plot. Placing a semicolon (<code>;</code>) at the end of <code>barplot()</code> will also do this for you. </p>
<p>When you run the code, the resulting plot will look like this:</p>
<figure class="js-lightbox"><a href="https://files.realpython.com/media/ie_daily_tips.53d0cdb6eb5d.png" target="_blank"><img loading="lazy" class="img-fluid mx-auto d-block " src="https://files.realpython.com/media/ie_daily_tips.53d0cdb6eb5d.png" width="708" height="561" srcset="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/ie_daily_tips.53d0cdb6eb5d.png&w=177&sig=094644e84ae714d81f254e60710ffedb71c2f983 177w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/ie_daily_tips.53d0cdb6eb5d.png&w=236&sig=41e9f8b944ab94f48624cfedc7b9393cd7d38fe9 236w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/ie_daily_tips.53d0cdb6eb5d.png&w=354&sig=9540e2d9af8c4189fd13cc3e6f073b427ccf910b 354w, https://files.realpython.com/media/ie_daily_tips.53d0cdb6eb5d.png 708w" sizes="(min-width: 1200px) 690px, (min-width: 780px) calc(-5vw + 669px), (min-width: 580px) 510px, calc(100vw - 30px)" alt="Barplot showing a waiter's daily tips." data-asset="5658"></a></figure>
<p>As you can see, the waiter’s daily average tips rise slightly on the weekends. It looks as though people tip more when they’re relaxed.</p>
<div class="alert alert-primary" role="alert">
<p><strong>Note:</strong> One thing you should be aware of is that <code>load_dataset()</code>, unlike <code>read_csv()</code>, will automatically convert string columns into the pandas <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html"><code>Categorical</code></a> data type for you. You use this where your data contains a limited, fixed number of possible values. In this case, the <code>day</code> column of data will be treated as a <code>Categorical</code> data type containing the days of the week. You can see this by using <code>tips["day"]</code> to view the column:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="ipython" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">In [2]: </span><span class="n">tips</span><span class="p">[</span><span class="s2">"day"</span><span class="p">]</span>
<span class="gh">Out[2]:</span>
<span class="go">0 Sun</span>
<span class="go">1 Sun</span>
<span class="go">2 Sun</span>
<span class="go">3 Sun</span>
<span class="go">4 Sun</span>
<span class="go"> ...</span>
<span class="go">239 Sat</span>
<span class="go">240 Sat</span>
<span class="go">241 Sat</span>
<span class="go">242 Sat</span>
<span class="go">243 Thur</span>
<span class="hll"><span class="go">Name: day, Length: 244, dtype: category</span>
</span><span class="hll"><span class="go">Categories (4, object): ['Thur', 'Fri', 'Sat', 'Sun']</span>
</span></code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>As you can see, your <code>day</code> column has a data type of <code>category</code>. Note, also, that while your original data starts with <code>Sun</code>, the first entry in the <code>category</code> is <code>Thur</code>. In creating the category, the days have been interpreted for you in the correct order. The <code>read_csv()</code> function doesn’t do this.</p>
</div>
</div><h2><a href="https://realpython.com/python-seaborn/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/python-seaborn/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python Basics Exercises: Dictionarieshttps://realpython.com/courses/basics-exercises-dictionaries/2024-03-12T14:00:00+00:00One of the most useful data structures in Python is the dictionary. In this video course, you’ll practice working with Python dictionaries, see how dictionaries differ from lists and tuples, and define and use dictionaries in your own code.
<p>In plain English, a dictionary is a book containing the definitions of words. Each entry in a dictionary has two parts: the word being defined, and its definition.</p>
<p><strong>Python dictionaries</strong>, like lists and tuples, store a collection of objects. However, instead of storing objects in a sequence, dictionaries hold
information in pairs of data called <strong>key-value pairs</strong>. That is, each object in a dictionary has two parts: a <strong>key</strong> and a <strong>value</strong>. Each key is assigned a single value, which defines the relationship between the two sets.</p>
<p><strong>In this video course, you’ll practice:</strong></p>
<ul>
<li>What a dictionary <strong>is</strong> and how it’s <strong>structured</strong></li>
<li>How dictionaries <strong>differ</strong> from other data structures</li>
<li>How to <strong>define</strong> and <strong>use</strong> dictionaries in your own code</li>
</ul>
<p>This video course is part of the Python Basics series, which accompanies <a href="https://realpython.com/products/python-basics-book/"><em>Python Basics: A Practical Introduction to Python 3</em></a>. You can also check out the other <a href="https://realpython.com/learning-paths/python-basics/">Python Basics courses</a>. </p>
<p>Note that you’ll be using <a href="https://realpython.com/python-idle/">IDLE</a> to <a href="https://realpython.com/interacting-with-python/">interact with Python</a> throughout this course.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python News: What's New From February 2024https://realpython.com/python-news-february-2024/2024-03-11T14:00:00+00:00February 2024 sees Python security updates and the introduction of a Rust-based tool for packaging, while the Python community gears up for PyCon US and the PSF enhances support with Grants Program Office Hours.
<div><p>As February takes a <a href="https://en.wikipedia.org/wiki/Leap_year">rare leap</a> forward with an extra day this year, the Python community followed suit!</p>
<p>Python versions 3.12 and 3.11 receive a <strong>security fix</strong>, and CPython source distributions now document the <strong>software supply chain</strong> to allow for a more effective vulnerability detection. Another Rust-based tool makes its way into the Python ecosystem, promising exciting improvements to the existing <strong>package management</strong> system.</p>
<p>Looking ahead, the reveal of the <strong>PyCon US 2024</strong> schedule gives us a glimpse into the upcoming Python conference. In other news, the Python Software Foundation launches recurring <strong>Office Hours</strong> to enhance community support in the Grants Program.</p>
<p>Let’s dive into the biggest <strong>Python news</strong> from the past month!</p>
<h2 id="python-312-and-311-receive-a-security-fix">Python 3.12 and 3.11 Receive a Security Fix<a class="headerlink" href="#python-312-and-311-receive-a-security-fix" title="Permanent link"></a></h2>
<p>The <a href="https://www.python.org/downloads/release/python-3122/">Python 3.12.2</a> and <a href="https://www.python.org/downloads/release/python-3118/">Python 3.11.8</a> patch versions were released, incorporating hundreds of commits and a host of bug fixes. Aside from that, they both provide a <a href="https://docs.python.org/release/3.12.2/whatsnew/changelog.html#security">small security fix</a> to an obscure feature of Python that allows for arbitrary code execution.</p>
<p>In a nutshell, this new security fix forbids the processing of hidden <strong>path configuration files</strong> (<code>.pth</code>) located in a virtual environment’s <code>site-packages/</code> folder:</p>
<div class="highlight"><pre><span></span><code>venv/
│
├── bin/
│
├── include/
│
├── lib/
│ │
│ └── python3.12/
│ │
│ └── site-packages/
│ │
<span class="hll">│ └── .your-hidden.pth
</span>│
├── lib64/
│
└── pyvenv.cfg
</code></pre></div>
<p>On a Unix-like operating system, any file becomes implicitly hidden when its name starts with a leading dot. On Windows, a file needs the corresponding attribute set to be hidden. Note that the directory structure presented above might look slightly different on Windows.</p>
<p>Path configuration files are plain text files that the <a href="https://docs.python.org/3/library/site.html#module-site"><code>site</code></a> module in the Python standard library automatically parses and processes upon the interpreter startup. Historically, these files helped facilitate <a href="https://setuptools.pypa.io/en/latest/userguide/development_mode.html">editable installs</a> and implement hooks into the <a href="https://realpython.com/python-import/">importing machinery</a>. They essentially let you append extra folders to the <strong>Python search path</strong>, which is accessible through the <code>sys.path</code> variable.</p>
<p>Unfortunately, <code>.pth</code> files have a quirk that makes it possible to execute any code on startup:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="text">
<div class="codeblock__header d-flex justify-content-between codeblock--grey">
<span class="mr-2 noselect" aria-label="Language">Text</span>
<span class="mr-2" aria-label="Filename"><code style="color: inherit;">venv/lib/python3.12/site-packages/.your-hidden.pth</code></span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code>import os; print("This will run on Python startup!")
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
</div><h2><a href="https://realpython.com/python-news-february-2024/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/python-news-february-2024/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #195: Building a Healthy Developer Mindset While Learning Pythonhttps://realpython.com/podcasts/rpp/195/2024-03-08T12:00:00+00:00How do you get yourself unstuck when facing a programming problem? How do you develop a positive developer mindset while learning Python? This week on the show, Bob Belderbos from Pybites is here to talk about learning Python and building healthy developer habits.
<p>How do you get yourself unstuck when facing a programming problem? How do you develop a positive developer mindset while learning Python? This week on the show, Bob Belderbos from Pybites is here to talk about learning Python and building healthy developer habits.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Build an LLM RAG Chatbot With LangChainhttps://realpython.com/build-llm-rag-chatbot-with-langchain/2024-03-06T14:00:00+00:00Large language models (LLMs) have taken the world by storm, demonstrating unprecedented capabilities in natural language tasks. In this step-by-step tutorial, you'll leverage LLMs to build your own retrieval-augmented generation (RAG) chatbot using synthetic data with LangChain and Neo4j.
<div><p>You’ve likely interacted with large language models (LLMs), like the ones behind OpenAI’s ChatGPT, and experienced their remarkable ability to answer questions, summarize documents, write code, and much more. While LLMs are remarkable by themselves, with a little programming knowledge, you can leverage libraries like <a href="https://python.langchain.com/docs/get_started/introduction">LangChain</a> to create your own LLM-powered chatbots that can do just about anything.</p>
<p>In an enterprise setting, one of the most popular ways to create an LLM-powered chatbot is through retrieval-augmented generation (RAG). When you design a RAG system, you use a retrieval model to retrieve relevant information, usually from a database or corpus, and provide this retrieved information to an LLM to generate contextually relevant responses.</p>
<p>In this tutorial, you’ll step into the shoes of an AI engineer working for a large hospital system. You’ll build a RAG chatbot in LangChain that uses <a href="https://neo4j.com/">Neo4j</a> to retrieve data about the patients, patient experiences, hospital locations, visits, insurance payers, and physicians in your hospital system.</p>
<p><strong>In this tutorial, you’ll learn how to</strong>:</p>
<ul>
<li>Use <strong>LangChain</strong> to build custom <strong>chatbots</strong></li>
<li><strong>Design</strong> a chatbot using your understanding of the business requirements and hospital system data</li>
<li>Work with <strong>graph databases</strong></li>
<li>Set up a <strong>Neo4j</strong> AuraDB instance</li>
<li>Build a <strong>RAG</strong> chatbot that retrieves both <strong>structured</strong> and <strong>unstructured</strong> data from Neo4j</li>
<li><strong>Deploy</strong> your chatbot with <strong>FastAPI</strong> and <strong>Streamlit</strong></li>
</ul>
<p>Click the link below to download the complete source code and data for this project:</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/build-llm-rag-chatbot-with-langchain-code/" class="alert-link" data-toggle="modal" data-target="#modal-build-llm-rag-chatbot-with-langchain-code" data-focus="false" markdown="1">Click here to download the free source code</a> for your LangChain chatbot.</p>
</div>
<h2 id="demo-an-llm-rag-chatbot-with-langchain-and-neo4j">Demo: An LLM RAG Chatbot With LangChain and Neo4j<a class="headerlink" href="#demo-an-llm-rag-chatbot-with-langchain-and-neo4j" title="Permanent link"></a></h2>
<p>By the end of this tutorial, you’ll have a <a href="https://realpython.com/api-integration-in-python/">REST API</a> that serves your LangChain chatbot. You’ll also have a <a href="https://streamlit.io/">Streamlit</a> app that provides a nice chat interface to interact with your API:</p>
<figure>
<div class="embed-responsive embed-responsive-16by9 rounded mb-3 border">
<iframe loading="lazy" class="embed-responsive-item" src="https://player.vimeo.com/video/918999422" frameborder="0" allow="fullscreen" allowfullscreen></iframe>
</div>
</figure>
<p>Under the hood, the Streamlit app sends your messages to the chatbot API, and the chatbot generates and sends a response back to the Streamlit app, which displays it to the user. </p>
<p>You’ll get an in-depth overview of the data that your chatbot has access to later, but if you’re anxious to test it out, you can ask questions similar to the examples given in the sidebar:</p>
<figure class="js-lightbox"><a href="https://files.realpython.com/media/Screenshot_2024-01-01_at_2.34.47_PM.fa9ed6c58d87.png" target="_blank"><img loading="lazy" class="img-fluid mx-auto d-block " src="https://files.realpython.com/media/Screenshot_2024-01-01_at_2.34.47_PM.fa9ed6c58d87.png" width="2686" height="1710" srcset="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/Screenshot_2024-01-01_at_2.34.47_PM.fa9ed6c58d87.png&w=671&sig=8dca32f0154574458d7f1f06fa043e70cc5c9b6f 671w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/Screenshot_2024-01-01_at_2.34.47_PM.fa9ed6c58d87.png&w=895&sig=419dc6ad2cda94fac29893c6ebffa9bc879f9150 895w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/Screenshot_2024-01-01_at_2.34.47_PM.fa9ed6c58d87.png&w=1343&sig=91d92233da6b80475093666845efb6a5e32e8885 1343w, https://files.realpython.com/media/Screenshot_2024-01-01_at_2.34.47_PM.fa9ed6c58d87.png 2686w" sizes="(min-width: 1200px) 690px, (min-width: 780px) calc(-5vw + 669px), (min-width: 580px) 510px, calc(100vw - 30px)" alt="Example questions that the chatbot can answer" data-asset="5619"></a><figcaption class="figure-caption text-center">Example questions can be found in the sidebar.</figcaption></figure>
<p>You’ll learn how to tackle each step, from understanding the business requirements and data to building the Streamlit app. There’s a lot to unpack in this tutorial, but don’t feel overwhelmed. You’ll get some background on each concept introduced, along with links to external sources that will deepen your understanding. Now, it’s time to dive in!</p>
<h2 id="prerequisites">Prerequisites<a class="headerlink" href="#prerequisites" title="Permanent link"></a></h2>
<p>This tutorial is best suited for intermediate Python developers who want to get hands-on experience creating custom chatbots. Aside from intermediate Python knowledge, you’ll benefit from having a high-level understanding of the following concepts and technologies:</p>
<ul>
<li>Large language models (LLMs) and <a href="https://realpython.com/practical-prompt-engineering/">prompt engineering</a></li>
<li><a href="https://realpython.com/chromadb-vector-database/#represent-data-as-vectors">Text embeddings and vector databases</a></li>
<li><a href="https://neo4j.com/developer/graph-database/">Graph databases</a> and <a href="https://neo4j.com/docs/getting-started/languages-guides/neo4j-python/">Neo4j</a></li>
<li><a href="https://openai.com/product">The OpenAI developer ecosystem</a></li>
<li><a href="https://realpython.com/api-integration-in-python/">REST APIs</a> and <a href="https://realpython.com/fastapi-python-web-apis/">FastAPI</a></li>
<li><a href="https://realpython.com/async-io-python/">Asynchronous programming</a></li>
<li><a href="https://realpython.com/tutorials/docker/">Docker</a> and <a href="https://docs.docker.com/compose/">Docker Compose</a></li>
</ul>
<p>Nothing listed above is a hard prerequisite, so don’t worry if you don’t feel knowledgeable in any of them. You’ll be introduced to each concept and technology along the way. Besides, there’s no better way to learn these prerequisites than to implement them yourself in this tutorial. </p>
<p>Next up, you’ll get a brief project overview and begin learning about LangChain.</p>
<h2 id="project-overview">Project Overview<a class="headerlink" href="#project-overview" title="Permanent link"></a></h2>
<p>Throughout this tutorial, you’ll create a few directories that make up your final chatbot. Here’s a breakdown of each directory:</p>
<ul>
<li>
<p><code>langchain_intro/</code> will help you get familiar with LangChain and equip you with the tools that you need to build the chatbot you saw in the demo, and it won’t be included in your final chatbot. You’ll cover this in <a href="#step-1-get-familiar-with-langchain">Step 1</a>.</p>
</li>
<li>
<p><code>data/</code> has the raw hospital system data stored as CSV files. You’ll explore this data in <a href="#step-2-understand-the-business-requirements-and-data">Step 2</a>. In <a href="#step-3-set-up-a-neo4j-graph-database">Step 3</a>, you’ll move this data into a Neo4j database that your chatbot will query to answer questions. </p>
</li>
<li>
<p><code>hospital_neo4j_etl/</code> contains a script that loads the raw data from <code>data/</code> into your Neo4j database. You have to run this before building your chatbot, and you’ll learn everything you need to know about setting up a Neo4j instance in <a href="#step-3-set-up-a-neo4j-graph-database">Step 3</a>.</p>
</li>
<li>
<p><code>chatbot_api/</code> is your <a href="https://realpython.com/fastapi-python-web-apis/">FastAPI</a> app that serves your chatbot as a REST endpoint, and it’s the core deliverable of this project. The <code>chatbot_api/src/agents/</code> and <code>chatbot_api/src/chains/</code> subdirectories contain the LangChain objects that comprise your chatbot. You’ll learn what agents and chains are later, but for now, just know that your chatbot is actually a LangChain agent composed of chains and functions. </p>
</li>
<li>
<p><code>tests/</code> includes two scripts that test how fast your chatbot can answer a series of questions. This will give you a feel for how much time you save by making asynchronous requests to LLM providers like OpenAI.</p>
</li>
<li>
<p><code>chatbot_frontend/</code> is your Streamlit app that interacts with the chatbot endpoint in <code>chatbot_api/</code>. This is the UI that you saw in the demo, and you’ll build this in <a href="#step-5-deploy-the-langchain-agent">Step 5</a>.</p>
</li>
</ul>
<p>All the environment variables needed to build and run your chatbot will be stored in a <code>.env</code> file. You’ll deploy the code in <code>hospital_neo4j_etl/</code>, <code>chatbot_api</code>, and <code>chatbot_frontend</code> as Docker containers that’ll be orchestrated with Docker Compose. If you want to experiment with the chatbot before going through the rest of this tutorial, then you can download the materials and follow the instructions in the README file to get things running:</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/build-llm-rag-chatbot-with-langchain-code/" class="alert-link" data-toggle="modal" data-target="#modal-build-llm-rag-chatbot-with-langchain-code" data-focus="false" markdown="1">Click here to download the free source code</a> for your LangChain chatbot.</p>
</div>
<p>With the project overview and prerequisites behind you, you’re ready to get started with the first step—getting familiar with LangChain.</p>
</div><h2><a href="https://realpython.com/build-llm-rag-chatbot-with-langchain/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/build-llm-rag-chatbot-with-langchain/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Creating Asynchronous Tasks With Celery and Djangohttps://realpython.com/courses/asynchronous-tasks-celery-django/2024-03-05T14:00:00+00:00In this video course, you'll learn how to integrate Celery and Django using Redis as a message broker. You'll refactor the synchronous email sending functionality of an existing Django app into an asynchronous task that you'll run with Celery instead.
<p>You’ve built a shiny <strong>Django</strong> app and want to release it to the public, but you’re worried about time-intensive tasks that are part of your app’s workflow. You don’t want your users to have a negative experience navigating your app. You can integrate <strong>Celery</strong> to help with that.</p>
<p>Celery is a <strong>distributed task queue</strong> for UNIX systems. It allows you to offload work from your Python app. Once you integrate Celery into your app, you can send time-intensive tasks to Celery’s task queue. That way, your web app can continue to respond quickly to users while Celery completes expensive operations asynchronously in the background.</p>
<p><strong>In this video course, you’ll learn how to:</strong></p>
<ul>
<li>Recognize <strong>effective use cases</strong> for Celery</li>
<li>Differentiate between <strong>Celery beat</strong> and <strong>Celery workers</strong></li>
<li><strong>Integrate Celery and Redis</strong> in a Django project</li>
<li>Set up <strong>asynchronous tasks</strong> that run independently of your Django app</li>
<li>Refactor Django code to <strong>run a task with Celery</strong> instead</li>
</ul>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python's __all__: Packages, Modules, and Wildcard Importshttps://realpython.com/python-all-attribute/2024-03-04T14:00:00+00:00In this tutorial, you'll learn about wildcard imports and the __all__ variable in Python. With __all__, you can prepare your packages and modules for wildcard imports, which are a quick way to import everything.
<div><p>Python has something called <strong>wildcard imports</strong>, which look like <code>from module import *</code>. This type of import allows you to quickly get all the objects from a module into your namespace. However, using this import on a package can be confusing because it’s not clear what you want to import: subpackages, modules, objects? Python has the <strong><code>__all__</code></strong> variable to work around this issue.</p>
<p>The <code>__all__</code> variable is a list of strings where each string represents the name of a variable, function, class, or module that you want to expose to wildcard imports.</p>
<p><strong>In this tutorial, you’ll:</strong></p>
<ul>
<li>Understand <strong>wildcard imports</strong> in Python</li>
<li>Use <strong><code>__all__</code></strong> to control the modules that you <strong>expose</strong> to wildcard imports</li>
<li>Control the <strong>names</strong> that you expose in <strong>modules</strong> and <strong>packages</strong></li>
<li>Explore <strong>other use cases</strong> of the <code>__all__</code> variable</li>
<li>Learn some <strong>benefits</strong> and <strong>best practices</strong> of using <code>__all__</code></li>
</ul>
<p>To get the most out of this tutorial, you should be familiar with a few Python concepts, including <a href="https://realpython.com/python-modules-packages/">modules and packages</a>, and the <a href="https://realpython.com/python-import/">import</a> system.</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/python-all-attribute-code/" class="alert-link" data-toggle="modal" data-target="#modal-python-all-attribute-code" data-focus="false" markdown="1">Click here to download the free sample code</a> that shows you how to use Python’s <code>__all__</code> attribute.</p>
</div>
<h2 id="importing-objects-in-python">Importing Objects in Python<a class="headerlink" href="#importing-objects-in-python" title="Permanent link"></a></h2>
<p>When creating a Python project or application, you’ll need a way to access code from the <a href="https://docs.python.org/3/library/index.html">standard library</a> or third-party libraries. You’ll also need to access your own code from the multiple files that may make up your project. Python’s <a href="https://docs.python.org/3/reference/import.html#the-import-system">import system</a> is the mechanism that allows you to do this.</p>
<p>The import system lets you get objects in different ways. You can use:</p>
<ul>
<li>Explicit imports</li>
<li>Wildcard imports</li>
</ul>
<p>In the following sections, you’ll learn the basics of both strategies. You’ll learn about the different syntax that you can use in each case and the result of running an <a href="https://realpython.com/python-import/"><code>import</code></a> statement.</p>
<h3 id="explicit-imports">Explicit Imports<a class="headerlink" href="#explicit-imports" title="Permanent link"></a></h3>
<p>In Python, when you need to get a specific object from a <a href="https://realpython.com/python-modules-packages/#python-modules-overview">module</a> or a particular module from a <a href="https://realpython.com/python-modules-packages/#python-packages">package</a>, you can use an <strong>explicit <code>import</code> statement</strong>. This type of statement allows you to bring the target object to your current <a href="https://realpython.com/python-namespaces-scope/">namespace</a> so that you can use the object in your code.</p>
<p>To import a module by its name, you can use the following syntax:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="python">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="kn">import</span> <span class="nn">module</span> <span class="p">[</span><span class="k">as</span> <span class="n">name</span><span class="p">]</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>This statement allows you to import a module by its name. The module must be listed in Python’s <a href="https://realpython.com/python-import/#pythons-import-path">import path</a>, which is a list of locations where the <a href="https://docs.python.org/3/glossary.html#term-path-based-finder">path based finder</a> searches when you run an import.</p>
<p>The part of the syntax that’s enclosed in square brackets is optional and allows you to create an <a href="https://realpython.com/python-mutable-vs-immutable-types/#aliasing-variables">alias</a> of the imported name. This practice can help you avoid name collisions in your code.</p>
<p>As an example, say that you have the following module:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="python">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<span class="mr-2" aria-label="Filename"><code style="color: inherit;">calculations.py</code></span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">subtract</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">multiply</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">a</span> <span class="o">*</span> <span class="n">b</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">divide</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">a</span> <span class="o">/</span> <span class="n">b</span><span class="p">)</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>This sample module provides functions that allow you to perform basic calculations. The containing module is called <code>calculations.py</code>. To import this module and use the functions in your code, go ahead and start a <a href="https://realpython.com/python-repl/">REPL</a> session in the same directory where you saved the file.</p>
<p>Then run the following code:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="pycon" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">calculations</span>
<span class="gp">>>> </span><span class="n">calculations</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">6.0</span>
<span class="gp">>>> </span><span class="n">calculations</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">4.0</span>
<span class="gp">>>> </span><span class="n">calculations</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">10.0</span>
<span class="gp">>>> </span><span class="n">calculations</span><span class="o">.</span><span class="n">divide</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">6.0</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>The <code>import</code> statement at the beginning of this code snippet brings the module name to your current namespace. To use the functions or any other object from <code>calculations</code>, you need to use fully <a href="https://docs.python.org/3/glossary.html#term-qualified-name">qualified names</a> with the dot notation.</p>
<div class="alert alert-primary" role="alert">
<p><strong>Note:</strong> You can create an alias of <code>calculations</code> using the following syntax:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="python">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="kn">import</span> <span class="nn">calculations</span> <span class="k">as</span> <span class="nn">calc</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>This practice allows you to avoid name clashes in your code. In some contexts, it’s also common practice to reduce the number of characters to type when using qualified names.</p>
<p>For example, if you’re familiar with libraries like <a href="https://realpython.com/numpy-tutorial/">NumPy</a> and <a href="https://realpython.com/python-pandas-tricks/">pandas</a>, then you’ll know that it’s common to use the following imports:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="python">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>Using shorter aliases when you import modules facilitates using their content by taking advantage of qualified names.</p>
</div>
<p>You can also use a similar syntax to import a Python package:</p>
</div><h2><a href="https://realpython.com/python-all-attribute/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/python-all-attribute/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #194: Automate Tasks With Python & Building a Small Search Enginehttps://realpython.com/podcasts/rpp/194/2024-03-01T12:00:00+00:00What are the typical computer tasks you do manually every week? Could you automate those tasks with a Python script? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.
<p>What are the typical computer tasks you do manually every week? Could you automate those tasks with a Python script? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python's Requests Library (Guide)https://realpython.com/python-requests/2024-02-28T14:00:00+00:00In this tutorial on Python's Requests library, you'll see some of the most useful features that Requests has to offer as well as ways to customize and optimize those features. You'll learn how to use requests efficiently and stop requests to external services from slowing down your application.
<div><p>The <a href="https://requests.readthedocs.io/en/latest/">Requests</a> library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.</p>
<p>Throughout this tutorial, you’ll see some of the most useful features that Requests has to offer as well as ways to customize and optimize those features for different situations that you may come across. You’ll also learn how to use Requests in an efficient way as well as how to prevent requests to external services from slowing down your application.</p>
<p><strong>In this tutorial, you’ll learn how to:</strong></p>
<ul>
<li><strong>Make requests</strong> using the most common HTTP methods</li>
<li><strong>Customize</strong> your requests’ headers and data using the query string and message body</li>
<li><strong>Inspect</strong> data from your requests and responses</li>
<li>Make <strong>authenticated</strong> requests</li>
<li><strong>Configure</strong> your requests to help prevent your application from backing up or slowing down</li>
</ul>
<p>For the best experience working through this tutorial, you should have <a href="https://www.w3schools.com/tags/ref_httpmethods.asp">basic general knowledge of HTTP</a>. That said, you still may be able to follow along fine without it.</p>
<p>In the upcoming sections, you’ll see how you can install and use <code>requests</code> in your application. If you want to play with the code examples that you’ll see in this tutorial, as well as some additional ones, then you can download the code examples and work with them locally:</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/python-requests-code/" class="alert-link" data-toggle="modal" data-target="#modal-python-requests-code" data-focus="false" markdown="1">Click here to download the free sample code</a> that shows you how to use Python’s Requests library.</p>
</div>
<div class="alert alert-primary" role="alert">
<p><strong><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@quiz"></use></svg></span> Take the Quiz:</strong> Test your knowledge with our interactive “HTTP Requests With the "requests" Library” quiz. Upon completion you will receive a score so you can track your learning progress over time:</p>
<p class="text-center my-2"><a class="btn btn-primary" href="/quizzes/python-requests/" target="_blank">Take the Quiz »</a></p>
</div>
<h2 id="getting-started-with-pythons-requests-library">Getting Started With Python’s Requests Library<a class="headerlink" href="#getting-started-with-pythons-requests-library" title="Permanent link"></a></h2>
<p>Even though the Requests library is a common staple for many Python developers, it’s not included in <a href="https://docs.python.org/3/library/index.html">Python’s standard library</a>. There are <a href="https://github.com/psf/requests/issues/2424">good reasons for that decision</a>, primarily that the library can continue to evolve more freely as a self-standing project.</p>
<div class="alert alert-primary" role="alert">
<p><strong>Note:</strong> Requests doesn’t support asynchronous HTTP requests directly. If you need <a href="https://realpython.com/async-io-python/">async</a> support in your program, you should try out <a href="https://docs.aiohttp.org/en/stable/">AIOHTTP</a> or <a href="https://www.python-httpx.org/async/">HTTPX</a>. The latter library is broadly compatible with Requests’ syntax.</p>
</div>
<p>Because Requests is a third-party library, you need to install it before you can use it in your code. As a good practice, you should install external packages into a <a href="https://realpython.com/python-virtual-environments-a-primer/">virtual environment</a>, but you may choose to install <code>requests</code> into your global environment if you’re planning to use it across multiple projects.</p>
<p>Whether you’re working in a virtual environment or not, you’ll need to install <code>requests</code>:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="console" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--yellow">
<span class="mr-2 noselect" aria-label="Language">Shell</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">$ </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>install<span class="w"> </span>requests
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>Once <a href="https://realpython.com/what-is-pip/"><code>pip</code></a> has finished installing <code>requests</code>, you can use it in your application. Importing <code>requests</code> looks like this:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="python">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="kn">import</span> <span class="nn">requests</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>Now that you’re all set up, it’s time to begin your journey through Requests. Your first goal will be learning how to make a <code>GET</code> request.</p>
<h2 id="the-get-request">The GET Request<a class="headerlink" href="#the-get-request" title="Permanent link"></a></h2>
<p><a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods">HTTP methods</a>, such as <code>GET</code> and <code>POST</code>, determine which action you’re trying to perform when making an HTTP request. Besides <code>GET</code> and <code>POST</code>, there are several other common methods that you’ll use later in this tutorial.</p>
<p>One of the most common HTTP methods is <code>GET</code>. The <code>GET</code> method indicates that you’re trying to get or retrieve data from a specified resource. To make a <code>GET</code> request using Requests, you can invoke <code>requests.get()</code>.</p>
<p>To test this out, you can make a <code>GET</code> request to <a href="https://docs.github.com/en/rest">GitHub’s REST API</a> by calling <code>get()</code> with the following URL:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="pycon" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">requests</span>
<span class="gp">>>> </span><span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"https://api.github.com"</span><span class="p">)</span>
<span class="go"><Response [200]></span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>Congratulations! You’ve made your first request. Now you’ll dive a little deeper into the response of that request.</p>
<h2 id="the-response">The Response<a class="headerlink" href="#the-response" title="Permanent link"></a></h2>
<p>A <code>Response</code> is a powerful object for inspecting the results of the request. Make that same request again, but this time store the return value in a <a href="https://realpython.com/python-variables/">variable</a> so that you can get a closer look at its attributes and behaviors:</p>
</div><h2><a href="https://realpython.com/python-requests/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/python-requests/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python Basics Exercises: Installing Packages With piphttps://realpython.com/courses/basics-exercises-install-packages-with-pip/2024-02-27T14:00:00+00:00In this Python Basics Exercises video course, you'll practice installing packages with pip. You'll also practice creating virtual environments, making lists of requirements, and recreating a development environment.
<p>So far on the <a href="https://realpython.com/learning-paths/python-basics/">Python Basics learning path</a>, you’ve been working within the bounds of the Python standard library. Now it’s time to unlock packages that aren’t included with Python by default. To do that, you’ll need <strong><code>pip</code></strong>.</p>
<p>Many programming languages offer a <strong>package manager</strong> that automates the process of installing, upgrading, and removing <strong>third-party packages</strong>. Python is no exception. The de facto package manager for Python is called <code>pip</code>. </p>
<p>In this Python Basics Exercises course, you’ll test and reinforce your knowledge of installing packages and managing virtual environments.</p>
<p><strong>In this video course, you’ll practice:</strong></p>
<ul>
<li><strong>Installing</strong> and <strong>managing</strong> third-party packages with <code>pip</code></li>
<li>Using <strong>virtual environments</strong> to separate project dependencies</li>
<li>Declaring <strong>requirements</strong> and <strong>re-create</strong> a development environment</li>
</ul>
<p>By the end of this course, you’ll have an even stronger grasp of installing packages to suit your programming needs</p>
<p>This video course is part of the Python Basics series, which accompanies <a href="https://realpython.com/products/python-basics-book/"><em>Python Basics: A Practical Introduction to Python 3</em></a>. Note that you’ll be using <a href="https://realpython.com/python-idle/">IDLE</a> to <a href="https://realpython.com/interacting-with-python/">interact with Python</a> throughout this course.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Duck Typing in Python: Writing Flexible and Decoupled Codehttps://realpython.com/duck-typing-python/2024-02-26T14:00:00+00:00In this tutorial, you'll learn about duck typing in Python. It's a typing system based on objects' behaviors rather than on inheritance. By taking advantage of duck typing, you can create flexible and decoupled sets of Python classes that you can use together or individually.
<div><p>Python makes extensive use of a <a href="https://realpython.com/python-type-checking/#type-systems">type system</a> known as <strong>duck typing</strong>. The system is based on objects’ behaviors and interfaces. Many built-in classes and tools support this type system, which makes them pretty flexible and decoupled.</p>
<p>Duck typing is a core concept in Python. Learning about the topic will help you understand how the language works and, more importantly, how to use this approach in your own code.</p>
<p><strong>In this tutorial, you’ll learn:</strong></p>
<ul>
<li>What <strong>duck typing</strong> is and what its pros and cons are</li>
<li>How Python’s classes and tools <strong>take advantage of duck typing</strong></li>
<li>How <strong>special methods</strong> and <strong>protocols</strong> support duck typing</li>
<li>What <strong>alternatives</strong> to duck typing you’ll have in Python</li>
</ul>
<p>To get the most out of this tutorial, you should be familiar with several Python concepts, including <a href="https://realpython.com/python3-object-oriented-programming/">object-oriented programming</a>, <a href="https://realpython.com/python-classes/">classes</a>, <a href="https://realpython.com/python-magic-methods/">special methods</a>, <a href="https://realpython.com/inheritance-composition-python/">inheritance</a>, and <a href="https://realpython.com/python-interface/">interfaces</a>.</p>
<div class="alert alert-warning" role="alert">
<p><strong markdown="1">Get Your Code:</strong> <a href="https://realpython.com/bonus/duck-typing-python-code/" class="alert-link" data-toggle="modal" data-target="#modal-duck-typing-python-code" data-focus="false" markdown="1">Click here to download the free sample code</a> that shows you how to use duck typing in Python.</p>
</div>
<h2 id="getting-to-know-duck-typing-in-python">Getting to Know Duck Typing in Python<a class="headerlink" href="#getting-to-know-duck-typing-in-python" title="Permanent link"></a></h2>
<p>In <a href="https://realpython.com/python3-object-oriented-programming/">object-oriented programming</a>, <a href="https://realpython.com/python-classes/">classes</a> mainly aim to encapsulate data and behaviors. Following this idea, you can replace any object with another if the replacement provides the same behaviors. This is true even if the implementation of the underlying behavior is radically different.</p>
<p>The code that uses the behaviors will work no matter what object provides it. This principle is the basis of a type system known as <a href="https://en.wikipedia.org/wiki/Duck_typing">duck typing</a>.</p>
<h3 id="duck-typing-behaving-like-a-duck">Duck Typing: Behaving Like a Duck<a class="headerlink" href="#duck-typing-behaving-like-a-duck" title="Permanent link"></a></h3>
<p>You’ll find many different definitions of duck typing out there. At its core, this coding style is based on a well-known saying:</p>
<blockquote>
<p>If it walks like a duck and it quacks like a duck, then it must be a duck.</p>
</blockquote>
<p>Extrapolating this to programming, you can have objects that <em>quack</em> like a duck and <em>walk</em> like a duck rather than asking whether those objects are ducks. In this context, <em>quack</em> and <em>walk</em> represent specific behaviors, which are part of the objects’ public interface (<a href="https://en.wikipedia.org/wiki/API">API</a>).</p>
<p>Duck typing is a <a href="https://en.wikipedia.org/wiki/Type_system">type system</a> where an object is considered compatible with a given type if it has all the <a href="https://realpython.com/python-classes/#providing-behavior-with-methods">methods</a> and <a href="https://realpython.com/python-classes/#attaching-data-to-classes-and-instances">attributes</a> that the type requires. This type system supports the ability to use objects of independent and decoupled classes in a specific context as long as they adhere to some common interface.</p>
<p>Duck typing is pretty popular in Python. The language documentation defines duck typing as shown below:</p>
<blockquote>
<p>A programming style which does not look at an object’s type to determine if it has the right interface; instead, the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution.</p>
<p>Duck-typing avoids tests using <a href="https://docs.python.org/3/library/functions.html#type"><code>type()</code></a> or <a href="https://docs.python.org/3/library/functions.html#isinstance"><code>isinstance()</code></a>. (Note, however, that duck-typing can be complemented with <a href="https://docs.python.org/3/glossary.html#term-abstract-base-class">abstract base classes</a>.) Instead, it typically employs <a href="https://docs.python.org/3/library/functions.html#hasattr"><code>hasattr()</code></a> tests or <a href="https://docs.python.org/3/glossary.html#term-EAFP">EAFP</a> programming. (<a href="https://docs.python.org/3/glossary.html#term-duck-typing">Source</a>)</p>
</blockquote>
<p>Here’s a quick example that involves birds that can swim and fly:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="python">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<span class="mr-2" aria-label="Filename"><code style="color: inherit;">birds_v1.py</code></span>
<div class="noselect">
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="k">class</span> <span class="nc">Duck</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">swim</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"The duck is swimming"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">fly</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"The duck is flying"</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Swan</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">swim</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"The swan is swimming"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">fly</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"The swan is flying"</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Albatross</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">swim</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"The albatross is swimming"</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">fly</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"The albatross is flying"</span><span class="p">)</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>In this example, your three birds can swim and fly. However, they’re completely independent classes. Because they share the same interface, you can use them in a flexible manner:</p>
<div class="codeblock mb-3 w-100" aria-label="Code block" data-syntax-language="pycon" data-is-repl="true">
<div class="codeblock__header d-flex justify-content-between codeblock--blue">
<span class="mr-2 noselect" aria-label="Language">Python</span>
<div class="noselect">
<span class="codeblock__output-toggle" title="Toggle prompts and output"><span class="icon baseline js-codeblock-output-on codeblock__header--icon-lower"><svg><use href="/static/icons.164c0b9d775c.svg#regular--rectangle-terminal"></use></svg></span></span>
</div>
</div>
<div style="position: relative;">
<div class="highlight highlight--with-header"><pre><span></span><code><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">birds_v1</span> <span class="kn">import</span> <span class="n">Duck</span><span class="p">,</span> <span class="n">Swan</span><span class="p">,</span> <span class="n">Albatross</span>
<span class="gp">>>> </span><span class="n">birds</span> <span class="o">=</span> <span class="p">[</span><span class="n">Duck</span><span class="p">(),</span> <span class="n">Swan</span><span class="p">(),</span> <span class="n">Albatross</span><span class="p">()]</span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">bird</span> <span class="ow">in</span> <span class="n">birds</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">bird</span><span class="o">.</span><span class="n">fly</span><span class="p">()</span>
<span class="gp">... </span> <span class="n">bird</span><span class="o">.</span><span class="n">swim</span><span class="p">()</span>
<span class="gp">...</span>
<span class="go">The duck is flying</span>
<span class="go">The duck is swimming</span>
<span class="go">The swan is flying</span>
<span class="go">The swan is swimming</span>
<span class="go">The albatross is flying</span>
<span class="go">The albatross is swimming</span>
</code></pre></div>
<button class="codeblock__copy btn btn-outline-secondary border m-1 px-1 d-hover-only" title="Copy to clipboard"><span class="icon baseline"><svg><use href="/static/icons.164c0b9d775c.svg#@copy"></use></svg></span></button>
<template class="codeblock__copied-template">
<span class="small"><span class="icon baseline mr-1 text-success"><svg><use href="/static/icons.164c0b9d775c.svg#@check"></use></svg></span>Copied!</span>
</template>
</div>
</div>
<p>Python doesn’t care about what object <code>bird</code> is holding at a given time. It just calls the expected methods. If the object provides the method, then the code works without breaking. That’s the flexibility that duck typing offers.</p>
<p>The duck typing system is pretty popular in Python. In most cases, you shouldn’t worry about making sure that an object is of the right type for using it in a certain piece of code. Instead, you can rely on objects that quack like ducks and walk like ducks.</p>
<h3 id="duck-typing-and-polymorphism">Duck Typing and Polymorphism<a class="headerlink" href="#duck-typing-and-polymorphism" title="Permanent link"></a></h3>
<p>In object-oriented programming, <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">polymorphism</a> allows you to treat objects of different types as the same general type. Polymorphism aims to enable code to work with objects of various types through a uniform interface (API), which helps you write more general and reusable code.</p>
<p>You’ll find different <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Forms">forms</a> of polymorphism in object-oriented programming. Duck typing is one of them.</p>
</div><h2><a href="https://realpython.com/duck-typing-python/?utm_source=realpython&utm_medium=rss">Read the full article at https://realpython.com/duck-typing-python/ »</a></h2>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #193: Wes McKinney on Improving the Data Stack & Composable Systemshttps://realpython.com/podcasts/rpp/193/2024-02-23T12:00:00+00:00How do you avoid the bottlenecks of data processing systems? Is it possible to build tools that decouple storage and computation? This week on the show, creator of the pandas library Wes McKinney is here to discuss Apache Arrow, composable data systems, and community collaboration.
<p>How do you avoid the bottlenecks of data processing systems? Is it possible to build tools that decouple storage and computation? This week on the show, creator of the pandas library Wes McKinney is here to discuss Apache Arrow, composable data systems, and community collaboration.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Unleashing the Power of the Console With Richhttps://realpython.com/courses/unleash-power-rich/2024-02-20T14:00:00+00:00Rich is a powerful library for creating text-based user interfaces (TUIs) in Python. It enhances code readability by pretty-printing complex data structures and adds visual appeal with colored text, tables, animations, and more.
<p>Python’s Rich package is a versatile tool kit that enables you to generate beautifully formatted and highlighted text in the console. It extends beyond this to help you build captivating text-based user interfaces (TUIs).</p>
<p>But why opt for a TUI instead of a graphical user interface (GUI)? There are instances where a text interface feels more fitting. Why employ a complex GUI for a simple application when an elegant text interface suffices? Working with plain text can be refreshing. It functions effortlessly across various hardware environments, including SSH terminals and single-board computer displays.</p>
<p>In this video course, you’ll discover how Rich can benefit you by:</p>
<ul>
<li>Enhancing the user interface of command-line tools</li>
<li>Improving the legibility of console output</li>
<li>Creating appealing dashboard displays for real-time tabular data</li>
<li>Generating well-formatted reports</li>
</ul>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #192: Practical Python Decorator Uses & Avoiding datetime Pitfallshttps://realpython.com/podcasts/rpp/192/2024-02-16T12:00:00+00:00What are real-life examples of using Python decorators? How can you harness their power in your code? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.
<p>What are real-life examples of using Python decorators? How can you harness their power in your code? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Create Conway's Game of Life With Pythonhttps://realpython.com/courses/conway-game-of-life-python/2024-02-13T14:00:00+00:00In this video course, you'll use Python to build Conway's Game of Life. You'll implement a user-friendly command-line interface (CLI) with several options that will allow you to run the game using different life patterns and configurations.
<p>Wouldn’t it be cool to build a Python game that only requires initial user input and then seems to take on a mind of its own, creating mesmerizing patterns along the way? You can do exactly that with <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway’s Game of Life</a>, which is about the evolution of cells in a life grid.</p>
<p>Implementing the Game of Life algorithm is a good exercise with many interesting challenges that you’ll have to figure out. Specifically, you’ll need to build the life grid and find a way to apply the game’s rules to all the cells on the grid so that they evolve through several generations.</p>
<p><strong>In this video course, you’ll:</strong></p>
<ul>
<li>Implement Conway’s <strong>Game of Life algorithm</strong> with Python</li>
<li>Build a <strong><code>curses</code> view</strong> to display the Game of Life grid</li>
<li>Create an <strong><code>argparse</code> command-line interface</strong> for the game</li>
<li>Set up the game app for <strong>installation</strong> and <strong>execution</strong></li>
</ul>
<p>To get the most out of this video course, you should know the basics of writing <a href="https://realpython.com/python3-object-oriented-programming/">object-oriented code</a> in Python, creating command-line interface (CLI) apps with <a href="https://realpython.com/command-line-interfaces-python-argparse/"><code>argparse</code></a>, and setting up a Python project.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #191: Focusing on Data Science & Less on Engineering and Dependencieshttps://realpython.com/podcasts/rpp/191/2024-02-09T12:00:00+00:00How do you manage the dependencies of a large-scale data science project? How do you migrate that project from a laptop to cloud infrastructure or utilize GPUs and multiple instances in parallel? This week on the show, Savin Goyal returns to discuss the updates to the open-source framework Metaflow.
<p>How do you manage the dependencies of a large-scale data science project? How do you migrate that project from a laptop to cloud infrastructure or utilize GPUs and multiple instances in parallel? This week on the show, Savin Goyal returns to discuss the updates to the open-source framework Metaflow.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python Basics Exercises: Lists and Tupleshttps://realpython.com/courses/python-basics-exercises-lists-tuples/2024-02-06T14:00:00+00:00In this Python Basics Exercises video course, you'll practice defining and manipulating Python lists and tuples in your code. By reinforcing your skills, you'll gain confidence in using lists and tuples in your programming projects.
<p>In <a href="https://realpython.com/courses/python-basics-lists-tuples/">Python Basics: Lists and Tuples</a>, you learned that <strong>Python lists</strong> resemble real-life lists in many ways. They serve as containers for organizing and storing collections of objects, allowing for the inclusion of different data types. You also learned about <strong>tuples</strong>, which are also collections of objects. However, while lists are <strong>mutable</strong>, tuples are <strong>immutable</strong>.</p>
<p>In this Python Basics Exercises course, you’ll test and reinforce your knowledge of Python lists and tuples. Along the way, you’ll also get experience with some good programming practices that will help you solve future challenges.</p>
<p><strong>In this video course, you’ll practice:</strong></p>
<ul>
<li>Defining and manipulating lists and tuples in Python</li>
<li>Leveraging the unique qualities of lists and tuples</li>
<li>Determining when you should use lists vs tuples</li>
</ul>
<p>By the end of this course, you’ll have an even stronger grasp of Python lists and tuples. You’ll be equipped with the knowledge to effectively incorporate them into your own programming projects.</p>
<p>This video course is part of the Python Basics series, which accompanies <a href="https://realpython.com/products/python-basics-book/"><em>Python Basics: A Practical Introduction to Python 3</em></a>. You can also check out the other <a href="https://realpython.com/learning-paths/python-basics/">Python Basics courses</a>. </p>
<p>Note that you’ll be using <a href="https://realpython.com/python-idle/">IDLE</a> to <a href="https://realpython.com/interacting-with-python/">interact with Python</a> throughout this course.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #190: Great Starting Points for Contributing to Open Sourcehttps://realpython.com/podcasts/rpp/190/2024-02-02T12:00:00+00:00What's it like to sit down for your first developer sprint at a conference? How do you find an appropriate issue to work on as a new open-source contributor? This week on the show, author and software engineer Stefanie Molin is here to discuss starting to contribute to open-source projects.
<p>What's it like to sit down for your first developer sprint at a conference? How do you find an appropriate issue to work on as a new open-source contributor? This week on the show, author and software engineer Stefanie Molin is here to discuss starting to contribute to open-source projects.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Building Enumerations With Python's enumhttps://realpython.com/courses/python-enum/2024-01-30T14:00:00+00:00In this video course, you'll discover the art of creating and using enumerations of logically connected constants in Python. To accomplish this, you'll explore the Enum class and other associated tools and types from the enum module from the Python standard library.
<p>Some programming languages, such as Java and C++, have built-in support for a data type called <strong>enumerations</strong>, commonly referred to as <strong>enums</strong>. Enums enable you to create sets of logically related constants that you can access through the enumeration itself. Unlike these languages, Python doesn’t have a dedicated syntax for enums. However, the Python <a href="https://docs.python.org/3/library/index.html">standard library</a> provides an <code>enum</code> module that offers support for enumerations through the <code>Enum</code> class.</p>
<p>If you’re familiar with enums from other languages and wish to use them in Python, or if you simply want to learn how to work with enumerations, then this video course is designed for you.</p>
<p><strong>In this video course, you’ll discover how to:</strong></p>
<ul>
<li>Create <strong>enumerations</strong> of constants using Python’s <strong><code>Enum</code></strong> class</li>
<li>Interact with enumerations and their <strong>members</strong> in Python</li>
<li>Customize enumeration classes by adding <strong>new functionalities</strong></li>
<li>Apply <strong>practical examples</strong> to gain a deeper understanding of the benefits of using enumerations</li>
</ul>
<p>Additionally, you’ll explore other specific enumeration types available in the <code>enum</code> module, such as <code>IntEnum</code>, <code>IntFlag</code>, and <code>Flag</code>. These specialized enums will expand your repertoire.</p>
<p>To get the most out of this video course, you should be familiar with <a href="https://realpython.com/python3-object-oriented-programming/">object-oriented programming</a> and <a href="https://realpython.com/inheritance-composition-python/">inheritance</a> in Python.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #189: Building a Python Debugger & Preparing for NumPy 2.0https://realpython.com/podcasts/rpp/189/2024-01-26T12:34:00+00:00How does a debugger work? What can you learn about Python by building one from scratch? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.
<p>How does a debugger work? What can you learn about Python by building one from scratch? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
Python Basics: Lists and Tupleshttps://realpython.com/courses/python-basics-lists-tuples/2024-01-23T14:00:00+00:00In this video course, you'll learn about Python lists and tuples, including how to define and manipulate them in your code. By the end of the course, you'll be ready to effectively use lists and tuples in your programming projects.
<p><strong>Python lists</strong> are similar to real-life lists. You can use them to store and organize a collection of objects, which can be of any data type. Instead of just storing one item, a list can hold multiple items while allowing manipulation and retrieval of those items. Because lists are <strong>mutable</strong>, you can think of them as being written in pencil. In other words, you can make changes.</p>
<p><strong>Tuples</strong>, on the other hand, are written in ink. They’re similar to lists in that they can hold multiple items, but unlike lists, tuples are <strong>immutable</strong>, meaning you can’t modify them after you’ve created them.</p>
<p><strong>In this video course, you’ll learn:</strong></p>
<ul>
<li>What lists and tuples are and how they’re structured</li>
<li>How lists and tuples differ from other data structures</li>
<li>How to define and manipulate lists and tuples in your Python code</li>
</ul>
<p>By the end of this course, you’ll have a solid understanding of Python lists and tuples, and you’ll be able to use them effectively in your own programming projects.</p>
<p>This video course is part of the Python Basics series, which accompanies <a href="https://realpython.com/products/python-basics-book/"><em>Python Basics: A Practical Introduction to Python 3</em></a>. You can also check out the other <a href="https://realpython.com/learning-paths/python-basics/">Python Basics courses</a>. </p>
<p>Note that you’ll be using <a href="https://realpython.com/python-idle/">IDLE</a> to <a href="https://realpython.com/interacting-with-python/">interact with Python</a> throughout this course.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>
The Real Python Podcast – Episode #188: Measuring Bias, Toxicity, and Truthfulness in LLMs With Pythonhttps://realpython.com/podcasts/rpp/188/2024-01-19T12:00:00+00:00How can you measure the quality of a large language model? What tools can measure bias, toxicity, and truthfulness levels in a model using Python? This week on the show, Jodie Burchell, developer advocate for data science at JetBrains, returns to discuss techniques and tools for evaluating LLMs With Python.
<p>How can you measure the quality of a large language model? What tools can measure bias, toxicity, and truthfulness levels in a model using Python? This week on the show, Jodie Burchell, developer advocate for data science at JetBrains, returns to discuss techniques and tools for evaluating LLMs With Python.</p>
<hr />
<p><em>[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. <a href="https://realpython.com/python-tricks/?utm_source=realpython&utm_medium=rss&utm_campaign=footer">>> Click here to learn more and see examples</a> ]</em></p>