Planet Python

Subscribe to Planet Python feed
Planet Python -
Updated: 8 min 29 sec ago

TechBeamers Python: Comparing Two Lists in Python

Fri, 2024-01-05 07:21

Comparing two lists is a common task in programming, and it becomes crucial when you need to find differences, and intersections, or validate data consistency. In this tutorial, we will explore various methods to compare two lists in Python. We’ll cover simple equality checks, membership testing, element-wise comparisons, and advanced techniques using built-in functions and […]

The post Comparing Two Lists in Python appeared first on TechBeamers.

Categories: FLOSS Project Planets

Real Python: The Real Python Podcast – Episode #186: Exploring Python in Excel

Fri, 2024-01-05 07:00

Are you interested in using your Python skills within Excel? Would you like to share a data science project or visualization as a single Office file? This week on the show, we speak with Principal Architect John Lam and Sr. Cloud Developer Advocate Sarah Kaiser from Microsoft about Python in Excel.

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

PyCharm: New Low-Impact Monitoring API in Python 3.12

Fri, 2024-01-05 06:12
People love PyCharm’s debugger, and we work hard to make it both fast and easy to use. But what if it could be even faster and easier to use? Python 3.12 adds the new low-impact monitoring API described in PEP 669, enabling debuggers, profilers, and similar tools to run code at almost full speed. As […]
Categories: FLOSS Project Planets

TechBeamers Python: How to Make a Unique List in Python

Fri, 2024-01-05 02:32

In the world of Python, handling data is a big deal. We often work with lists, and sometimes, we need to make sure they only have unique items. In this detailed guide, we’ll explore different ways to make a unique list in Python. From using sets to more advanced stuff like functools.reduce(), we’re going to […]

The post How to Make a Unique List in Python appeared first on TechBeamers.

Categories: FLOSS Project Planets

TechBeamers Python: 25 Sampling Interview Questions and Answers to Remember

Fri, 2024-01-05 02:07

Find out 25 commonly asked sampling interview questions distributed across different categories. These questions cover a range of topics related to sampling and can be used to assess the interviewee’s understanding of fundamental concepts, methods, and applications in various fields. 25 Sampling Interview Questions and Answers We have prepared this quick guide of sampling interview […]

The post 25 Sampling Interview Questions and Answers to Remember appeared first on TechBeamers.

Categories: FLOSS Project Planets

TechBeamers Python: Python Syntax – Quick Start Guide

Fri, 2024-01-05 00:16

Python, the language known for its simplicity and friendliness, has a way of writing code called syntax. It’s like the grammar of Python, telling you how to structure your code so the computer can understand and execute it. In this guide, we’re going to break down different parts of Python syntax, with clear explanations and […]

The post Python Syntax – Quick Start Guide appeared first on TechBeamers.

Categories: FLOSS Project Planets

TechBeamers Python: How to Achieve Python String indexOf Using Find() and Index()

Thu, 2024-01-04 12:10

The indexOf method helps locate a substring in a string, pointing to its first appearance. In Python, there isn’t a direct string indexOf method. But we can achieve the same functionality using various string indexing and search methods. In this tutorial, we’ll delve into these methods, providing multiple examples and additional information to help readers […]

The post How to Achieve Python String indexOf Using Find() and Index() appeared first on TechBeamers.

Categories: FLOSS Project Planets

Django Weblog: Unlock Early Savings: Early Bird Tickets for DjangoCon Europe 2024 Now Available!

Thu, 2024-01-04 11:52

You can take advantage of our Early Bird ticket sale for DjangoCon Europe 2024. By purchasing your tickets early, you not only guarantee your attendance at one of the most exciting Django events but also enjoy significant savings.

Buy tickets on the conference website

Why Go Early?

You can secure your tickets at a special Early Bird rate, providing exceptional value for your conference experience.

Also, your early commitment goes a long way in supporting the success of DjangoCon Europe 2024. It helps us plan better and ensure a seamless event.

Act now and secure your Early Bird tickets before the sale closes on April 31st. Don't miss out on the chance to save and be a part of this exciting event.

We can't wait to welcome you to DjangoCon Europe 2024!

Categories: FLOSS Project Planets

TechBeamers Python: A Beginner’s Guide to Python Random Sampling

Thu, 2024-01-04 09:07

Random sampling might sound complicated, but it’s a super useful skill when working with data in Python. It helps you pick out bits of information without going through everything. Python’s got this cool toolbox called the random module that makes random sampling a breeze. In this tutorial, we’re going to explore different ways to use […]

The post A Beginner’s Guide to Python Random Sampling appeared first on TechBeamers.

Categories: FLOSS Project Planets

Mark Dufour: Fast DOOM WAD renderer in 999 lines of Python

Wed, 2024-01-03 20:02

For the longest time, I've wanted to re-implement the original DOOM engine in Python, and compile it with Shedskin to get reasonable performance. So when I finally ran across a pretty small engine written in Java, by Leonardo Ono, I decided to convert his version to Python.

I left out some optimizations (most notably "visplanes"), for readability and in order to keep everything under 1000 lines of code (while following PEP8). So it could run quite a bit faster still. This is including a WAD loader and interactive Pygame wrapper, that makes it almost feel like you are playing DOOM.

It's interesting how using Python (using just CPython) seems to be about as fast as using assembler back in the day.

This video shows the day-and-night difference in FPS after compilation using Shedskin.

The source code can be found in the Shedskin examples directory.

I may revisit the code now and then, to try and improve readability by adding comments and/or refactoring parts. Patches in this direction very much welcome of course.

In general, we are also always looking to receive more feedback and contributions from the community! While not the 'final' solution to Python performance, Shed Skin is great fun to hack on. See some potential issues for the next release to start looking into.

Categories: FLOSS Project Planets

Matt Layman: Legal and Stripe - Building SaaS with Python and Django #179

Wed, 2024-01-03 19:00
In this episode, we took care of the legal obligations of the site by setting up Terms of Service and a Privacy Policy page. Then we moved on to the next portion of signup, which is to configure Stripe to create customers and prepare, ultimately, to accept subscription payments.
Categories: FLOSS Project Planets

Ben Cook: Saving Utility Companies Years with Computer Vision

Wed, 2024-01-03 13:15

How do utility companies monitor thousands of miles of electrical wire to find small imperfections that threaten the entire system? For the entire history of electrical infrastructure, the only answer has been ‘very slowly.’

Now, Sparrow’s computer vision capabilities, combined with Fast Forward’s thermal imaging system, can accomplish what used to take over a decade in less than a month. Here’s how they do it.

How it Started

Dusty Birge, CEO of Fast Forward began inspecting power lines using a drone and crowd-sourced labor. He knew that automation would be needed to take the next step forward, but he found people in the artificial intelligence space to be overconfident and unreliable. That is until he was introduced to Ben Cook, the founder of Sparrow Computing.

Within a month, Ben provided a computer vision model that could accurately identify utility poles, and that has been continually improving ever since.

The Project

Fast Forward rigged a system of 5 thermal cameras to a car and set them to take photos every 15 feet. Sparrow’s computer vision model then ran through the nearly 2 million photos taken and extracted about 50,000 relevant images, detecting any abnormalities in the utility lines.

“Right out of the gate, we presented data to the utilities and just blew them away,” Dusty said in an interview. “The first test runs proved a scalable model that automatically monitored a company’s entire system in under a month, where traditional methods would take over a decade. These test runs successfully spotted anomalies that would have caused blackouts, but were instead able to be fixed promptly.”

The numbers speak plainly for themselves, not just in time but in cost as well. There was one hotspot that Sparrow identified, but that the utility company did not address in time. The power line failed as a result, costing the company around $800. The inspection itself cost only $4. The potential return of this technology is astronomical, and it is already being put to good use.

Going Forward

Fast Forward is already looking ahead to the next phase of this project, translating the same process to daytime cameras. Having had such success in the initial tests, Dusty is pleased to continue working with Ben and Sparrow Computing.

Ben is excited to find more real world problems that can be solved as cameras become cheaper and more ubiquitous. He wants to create more computer vision models that interact with the physical environment and revolutionize companies throughout the Midwest and the world.

To get a closer look at Sparrow Computing, reach Ben at

The post Saving Utility Companies Years with Computer Vision appeared first on Sparrow Computing.

Categories: FLOSS Project Planets

Mirek Długosz: Playwright - accessing page object in event handler

Wed, 2024-01-03 12:37

Playwright exposes a number of browser events and provides a mechanism to respond to them. Since many of these events signal errors and problems, most of the time you want to log them, halt program execution, or ignore and move on. Logging is also shown in Playwright documentation about network, which I will use as a base for examples in this article.

Problem statement

Documentation shows event handlers created with lambda expressions, but lambda poses significant problems once you leave the territory of toy examples:

  • they should fit in single line of code
  • you can’t share them across modules
  • you can’t unit test them in isolation

Usually you want to define event handlers as normal functions. But when you attempt that, you might run into another problem - Playwright invokes event handler with some event-related data, that data does not contain any reference back to page object, and page object might contain some important contextual information.

In other words, we would like to do something similar to code below. Note that this example does not work - if you run it, you will get NameError: name 'page' is not defined.

from playwright.sync_api import sync_playwright from playwright.sync_api import Playwright def request_handler(request): print(f"{page.url} issued request: {request.method} {request.url}") def response_handler(response): print(f"{page.url} received response: {response.status} {response.url}") def run_test(playwright: Playwright): browser = playwright.chromium.launch() page = browser.new_page() page.goto("") page.on("request", request_handler) page.on("response", response_handler) page.goto("") browser.close() with sync_playwright() as playwright: run_test(playwright)

I can think of three ways of solving that: by defining a function inside a function, with functools.partialand with a factory function. Let’s take a look at all of them.

Defining a function inside a function

Most Python users are so used to defining functions at the top level of module or inside a class (we call these “methods”) that they might consider function definitions to be somewhat special. In fact, some other programming languages do encumber where functions can be defined. But in Python you can define them anywhere, including inside other functions.

from playwright.sync_api import sync_playwright from playwright.sync_api import Playwright def run_test(playwright: Playwright): def request_handler(request): print(f"{page.url} issued request: {request.method} {request.url}") def response_handler(response): print(f"{page.url} received response: {response.status} {response.url}") browser = playwright.chromium.launch() page = browser.new_page() page.goto("") page.on("request", request_handler) page.on("response", response_handler) page.goto("") browser.close() with sync_playwright() as playwright: run_test(playwright)

This works because function body is not evaluated until function is called and functions have access to names defined in their encompassing scope. So Python will look up page only when event handler is invoked by Playwright; since it’s not defined in function itself, Python will look for it in the function where event handler was defined (and then next function, if there is one, then module and eventually builtins).

I think this solution solves the most important part of the problem - it allows to write event handlers that span multiple lines. Technically it is also possible to share these handlers across modules, but you won’t see that often. They can’t be unit tested in isolation, as they depend on their parent function.


functools.partial documentation may be confusing, as prose sounds exactly like a description of standard function, code equivalent assumes pretty good understanding of Python internals, and provided example seems completely unnecessary.

I think about partial this way: it creates a function that has some of the arguments already filled in.

To be fair, partial is rarely needed. It allows to write shorter code, as you don’t have to repeat the same arguments over and over again. It may also allow you to provide saner library API - you can define single generic and flexible function with a lot of arguments, and few helper functions intended for external use, each with a small number of arguments.

But it’s invaluable when you have to provide your own function, but you don’t have control over arguments it will receive. Which is exactly the problem we are facing.

from functools import partial from playwright.sync_api import sync_playwright from playwright.sync_api import Playwright def request_handler(request, page=None): print(f"{page.url} issued request: {request.method} {request.url}") def response_handler(response, page=None): print(f"{page.url} received response: {response.status} {response.url}") def run_test(playwright: Playwright): browser = playwright.chromium.launch() page = browser.new_page() page.goto("") local_request_handler = partial(request_handler, page=page) local_response_handler = partial(response_handler, page=page) page.on("request", local_request_handler) page.on("response", local_response_handler) page.goto("") browser.close() with sync_playwright() as playwright: run_test(playwright)

Notice that our function takes the same arguments as Playwright event handler, and then some. When it’s time to assign event handlers, we use partial to create a new function, one that only needs argument that we will receive from Playwright - the other one is already filled in. But when function is executed, it will receive both arguments.

Factory function

Functions in Python may not only define other functions in their bodies, but also return functions. They are called “higher-order functions” and aren’t used often, with one notable exception of decorators.

from playwright.sync_api import sync_playwright from playwright.sync_api import Playwright def request_handler_factory(page): def inner(request): print(f"{page.url} issued request: {request.method} {request.url}") return inner def response_handler_factory(page): def inner(response): print(f"{page.url} received response: {response.status} {response.url}") return inner def run_test(playwright: Playwright): browser = playwright.chromium.launch() page = browser.new_page() page.goto("") page.on("request", request_handler_factory(page)) page.on("response", response_handler_factory(page)) page.goto("") browser.close() with sync_playwright() as playwright: run_test(playwright)

The key here is that inner function has access to all of enclosing scope, including values passed as arguments to outer function. This allows us to pass specific values that are only available in the place where outer function is called.


The first solution is a little different than other two, because it does not solve all of the problems set forth. On the other hand, I think it’s the easiest to understand - even beginner Python programmers should intuitively grasp what is happening and why.

In my experience higher-order functions takes some getting used to, while partial is not well-known and may be confusing at first. But they do solve our problem completely.

Categories: FLOSS Project Planets

Programiz: Python Dictionary

Wed, 2024-01-03 11:22
In this tutorial, you will learn about Python dictionaries - how they are created, how to access, add, and remove elements from them, and the various built-in methods associated with dictionaries.
Categories: FLOSS Project Planets

Programiz: Python for loop

Wed, 2024-01-03 10:58
In this article, we'll learn how to use a for loop in Python with the help of examples.
Categories: FLOSS Project Planets

Real Python: Python's Magic Methods: Leverage Their Power in Your Classes

Wed, 2024-01-03 09:00

As a Python developer who wants to harness the power of object-oriented programming, you’ll love to learn how to customize your classes using special methods, also known as magic methods or dunder methods. A special method is a method whose name starts and ends with a double underscore. These methods have special meanings for Python.

Python automatically calls magic methods as a response to certain operations, such as instantiation, sequence indexing, attribute managing, and much more. Magic methods support core object-oriented features in Python, so learning about them is fundamental for you as a Python programmer.

In this tutorial, you’ll:

  • Learn what Python’s special or magic methods are
  • Understand the magic behind magic methods in Python
  • Customize different behaviors of your custom classes with special methods

To get the most out of this tutorial, you should be familiar with general Python programming. More importantly, you should know the basics of object-oriented programming and classes in Python.

Get Your Code: Click here to download the free sample code that shows you how to use Python’s magic methods in your classes.

Getting to Know Python’s Magic or Special Methods

In Python, special methods are also called magic methods, or dunder methods. This latter terminology, dunder, refers to a particular naming convention that Python uses to name its special methods and attributes. The convention is to use double leading and trailing underscores in the name at hand, so it looks like .__method__().

Note: In this tutorial, you’ll find the terms special methods, dunder methods, and magic methods used interchangeably.

The double underscores flag these methods as core to some Python features. They help avoid name collisions with your own methods and attributes. Some popular and well-known magic methods include the following:

Special Method Description .__init__() Provides an initializer in Python classes .__str__() and .__repr__() Provide string representations for objects .__call__() Makes the instances of a class callable .__len__() Supports the len() function

This is just a tiny sample of all the special methods that Python has. All these methods support specific features that are core to Python and its object-oriented infrastructure.

Note: For the complete list of magic methods, refer to the special method section on the data model page of Python’s official documentation.

The Python documentation organizes the methods into several distinct groups:

Take a look at the documentation for more details on how the methods work and how to use them according to your specific needs.

Here’s how the Python documentation defines the term special methods:

A method that is called implicitly by Python to execute a certain operation on a type, such as addition. Such methods have names starting and ending with double underscores. (Source)

There’s an important detail to highlight in this definition. Python implicitly calls special methods to execute certain operations in your code. For example, when you run the addition 5 + 2 in a REPL session, Python internally runs the following code under the hood:

Python >>> (5).__add__(2) 7 Copied!

The .__add__() special method of integer numbers supports the addition that you typically run as 5 + 2.

Reading between the lines, you’ll realize that even though you can directly call special methods, they’re not intended for direct use. You shouldn’t call them directly in your code. Instead, you should rely on Python to call them automatically in response to a given operation.

Note: Even though special methods are also called magic methods, some people in the Python community may not like this latter terminology. The only magic around these methods is that Python calls them implicitly under the hood. So, the official documentation refers to them as special methods instead.

Magic methods exist for many purposes. All the available magic methods support built-in features and play specific roles in the language. For example, built-in types such as lists, strings, and dictionaries implement most of their core functionality using magic methods. In your custom classes, you can use magic methods to make callable objects, define how objects are compared, tweak how you create objects, and more.

Note that because magic methods have special meaning for Python itself, you should avoid naming custom methods using leading and trailing double underscores. Your custom method won’t trigger any Python action if its name doesn’t match any official special method names, but it’ll certainly confuse other programmers. New dunder names may also be introduced in future versions of Python.

Magic methods are core to Python’s data model and are a fundamental part of object-oriented programming in Python. In the following sections, you’ll learn about some of the most commonly used special methods. They’ll help you write better object-oriented code in your day-to-day programming adventure.

Controlling the Object Creation Process

When creating custom classes in Python, probably the first and most common method that you implement is .__init__(). This method works as an initializer because it allows you to provide initial values to any instance attributes that you define in your classes.

Read the full article at »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

PyCharm: How To Learn Django: A Comprehensive Guide for Beginners

Wed, 2024-01-03 05:56
Learning Django can be an exciting journey for anyone looking to develop web applications, but it can be intimidating at first. In this article, we’ll provide you with a comprehensive guide on how to learn Django effectively. We’ll explore the prerequisites, the time it takes to become proficient, and various resources to help you master […]
Categories: FLOSS Project Planets

Brett Cannon: An experimental pip subcommand for the Python Launcher for Unix

Wed, 2024-01-03 00:49

There are a couple of things I always want to be true when I install Python packages for a project:

  1. I have a virtual environment
  2. Pip is up-to-date

For virtual environments, you would like them to be created as fast as possible and (usually) with the newest version of Python. For keeping pip up-to-date, it would be nice to not have to do that for every single virtual environment you have.

To help make all of this true for myself, I created an experimental Python Launcher for Unix "subcommand": py-pip. The CLI app does the following:

  1. Makes sure there is a globally cached copy of pip, and updates it if necessary
  2. Uses the Python Launcher for Unix to create a virtual environment where it finds a pyproject.toml file
  3. Runs pip using the virtual environment&aposs interpreter

This is all done via a py-pip.pyz file (which you can rename to just py-pip if you want). The py-pip.pyz file available from a release of py-pip can be made executable (e.g. chmod a+x py-pip.pyz). The shebang of the file is already set to #!/usr/bin/env py so it&aposs ready to use the newest version of Python you have installed. Stick that on your PATH and you can then use that instead of py -m pip to run pip itself.

To keep pip up-to-date, the easiest way to do that is to have only a single copy of pip to worry about. Thanks to the pip team releasing a self-contained pip.pyz along with pip always working with supported, it means if we just cache a copy of pip.pyz and keep that up-to-date then we can have that one copy to worry about.

Having a single copy of pip also means we don&apost need to install pip for each virtual environment. That lets us use microvenv and skip the overhead of installing pip in each virtual environment.

Now, this is an experiment. Much like the Python Launcher for Unix, py-pip is somewhat optimized for my own workflow. I am also keeping an eye on PEP 723 and PEP 735 as a way to only install packages that have been written down somewhere instead of ever installing a package à la carte as I think that&aposs a better practice to follow and might actually trump all of this. But since I have seen others have frustration from both forgetting the virtual environment and having to keep pip up-to-date, I decided to open source the code.

Categories: FLOSS Project Planets

PyCoder’s Weekly: Issue #610 (Jan. 2, 2024)

Tue, 2024-01-02 14:30

#610 – JANUARY 2, 2024
View in Browser »

Build a Scalable Flask Web Project From Scratch

In this tutorial, you’ll explore the process of creating a boilerplate for a Flask web project. It’s a great starting point for any scalable Flask web app that you wish to develop in the future, from basic web pages to complex web applications.

JIT Coming to Python 3.13

Slides related to the upcoming JIT commit for Python 3.13. Note, GitHub paginates it if you don’t download it, so click the “More Pages” button to keep reading.

The Biggest Discoveries in Computer Science in 2023

Although 2023 was full of AI news in computer science, it wasn’t the only news. This article summarizes the breakthroughs in 2023.

PyCon US Received Record Number of Submissions


Python Jobs Senior Python Architect and Tech Lead (America)

Six Feet Up

Python Tutorial Editor (Anywhere)

Real Python

More Python Jobs >>>

Articles & Tutorials Python, C, Assembly – 2,500x Faster Cosine Similarity

Cosine similarity is a check to see if two vectors point in the same direction, regardless of magnitude. This test is frequently used in some machine learning algorithms. This article details the various steps in speeding up the code, starting with vanilla Python and going all the way down to hand tuned assembly language.

PyCoder’s Weekly 2023 Wrap Up

It’s been a fascinating year for the Python language and community. PyCoder’s Weekly included over 1,500 links to articles, blog posts, tutorials, and projects in 2023. Christopher Trudeau is back on the show this week to help wrap up everything by sharing some highlights and Python trends from across the year.

Python’s Soft Keywords

Python includes soft keywords: tokens that are important to the parser but can also be used as variable names. This article shows you what a soft keyword is and how to find them in Python 3.12 (both the easy and hard way).

The State of Developer Ecosystem in 2023

This is a cross-language developer survey of tools used in the industry. It includes questions about AI adoption, cloud tools, and more. 54% of respondents use Python as their most frequent language.

Build an Instant Messaging App With Django

This articles shows you how to take advantage of some the newer async mechanisms in Django to build a messaging app. Things that used to require a third party library are now part of the framework.
TOM DEKAN • Shared by Tom Dekan

Majority and Frequent Elements: Boyer Moore and Misra Gries

The Boyer-Moore majority vote algorithm looks for an element that appears more than n/2 times in a sequence using O(n) time. This article shows you how it works using Python code.

Why Should You Become an Engineering Manager?

Many developers dread the idea of becoming a manager, but there are some things you can only learn by doing. This article outlines why management might be the right thing for you.

Banish State-Mutating Methods From Data Classes

Redowan has strong opinions on reserving dataclasses for data-class purposes only: their methods should have no data modification side-effects. This article outlines why.

Django 5.0 Is Out!

Django 5 was recently released and this in-depth article covers what changed, how to upgrade from an earlier version, and how the Django version numbering system works.

How Many CPU Cores Can You Actually Use in Parallel?

“Figuring out how much parallelism your program can use is surprisingly tricky.” This article shows you why it is complicated and what you can determine.

TIL: Forcing pip to Use virtualenv

A quick tip on how to set an environment variable so that pip refuses to install a package unless in an active virtual environment.

Configuration in Python Applications

This post talks about how to store configuration for your script and how and when to load the information into your program.

Raise the Right Exceptions

Knowing when to raise the right exception is important, but often you don’t have to: Python might do it for you.

Projects & Code pyapp: Build Self-Bootstrapped Python Applications


django-tui: Inspect and Run Django Commands in a TUI


cicada: FOSS, Cross-Platform GitHub Actions


marker: Convert PDF to Markdown


Amphion: Toolkit for Audio, Music, and Speech Generation


Events Weekly Real Python Office Hours Q&A (Virtual)

January 3, 2024

Canberra Python Meetup

January 4, 2024

Sydney Python User Group (SyPy)

January 4, 2024

PiterPy Meetup

January 9, 2024

Leipzig Python User Group Meeting

January 9, 2024

Building Python Communities Around Python for Kids

January 10 to January 11, 2024

Happy Pythoning!
This was PyCoder’s Weekly Issue #610.
View in Browser »

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

Categories: FLOSS Project Planets

Hynek Schlawack: How to Ditch Codecov for Python Projects

Tue, 2024-01-02 11:39

Codecov’s unreliability breaking CI on my open source projects has been a constant source of frustration for me for years. I have found a way to enforce coverage over a whole GitHub Actions build matrix that doesn’t rely on third-party services.

Categories: FLOSS Project Planets