Planet Python

Subscribe to Planet Python feed
Planet Python - http://planetpython.org/
Updated: 17 hours 31 min ago

Python Insider: Python 3.12.2 and 3.11.8 are now available.

Wed, 2024-02-07 05:07

Python 3.12.2 and 3.11.8 are now available. In addition to all the usual bugfixes, these releases contain a small security fix: hidden .pth files are no longer automatically read and executed as part of Python startup. (New releases of 3.8, 3.9 and 3.10 containing the same fix are expected next week.)  Python 3.12.2

https://www.python.org/downloads/release/python-3122/

Python 3.12’s second bugfix release. In addition to the mentioned security fix and the usual slew of bug fixes, build changes and documentation updates (more than 350 commits), this is also the first release to include a Software Bill-of-Materials for the source packages (Python-3.12.2.tgz and Python-3.12.2.tar.xz). Full changelogPython 3.11.8

https://www.python.org/downloads/release/python-3118/

More than 300 commits of bug fixes, build changes and documentation updates. Full changelog.

 

We hope you enjoy the new releases!  Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself, or through contributions to the Python Software Foundation or CPython itself.  Thomas Wouters
on behalf of your release team,  Ned DeilySteve Dower
Pablo Galindo Salgado
Łukasz Langa
Categories: FLOSS Project Planets

Test and Code: 214: Python Testing in VS Code

Wed, 2024-02-07 00:20

If you haven't tried running automated tests, especially with pytest,  in VS Code recently, you should take another look.
The Python for VS Code interface for testing, especially for pytest, has changed recently. 
On this episode we discuss the change with the software engineer working on the pytest changes, Eleanor Boyd, and the product manager, Courtney Webster. 

Links from the episode:


The Complete pytest Course

<p>If you haven't tried running automated tests, especially with pytest,  in VS Code recently, you should take another look.<br>The Python for VS Code interface for testing, especially for pytest, has changed recently. <br>On this episode we discuss the change with the software engineer working on the pytest changes, Eleanor Boyd, and the product manager, Courtney Webster. </p><p>Links from the episode:</p><ul><li><a href="https://devblogs.microsoft.com/python/python-in-visual-studio-code-june-2023-release/#test-discovery-and-execution-rewrite">Blog post announcing the rewrite</a> <a href="https://devblogs.microsoft.com/python/python-in-visual-studio-code-june-2023-release/#test-discovery-and-execution-rewrite"> </a></li><li><a href="https://github.com/microsoft/vscode-python">Code repo for questions, comments, issues etc</a></li></ul> <br><p><strong>The Complete pytest Course</strong></p><ul><li>Level up your testing skills and save time during coding and maintenance.</li><li>Check out <a href="https://courses.pythontest.com/p/complete-pytest-course">courses.pythontest.com</a></li></ul>
Categories: FLOSS Project Planets

Andrea Grandi: How to show a cover image in Pelican based blog posts

Tue, 2024-02-06 16:03

How to add a cover image to Pelican based blog posts, so that when the article is shared on social media the image is shown in the preview.

Categories: FLOSS Project Planets

PyCoder’s Weekly: Issue #615 (Feb. 6, 2024)

Tue, 2024-02-06 14:30

#615 – FEBRUARY 6, 2024
View in Browser »

Rye: A [Python Developer Experience] Vision Continued

Armin, who’s also the creator of Flask, discusses the continued development of Rye, a tool he created to improve the Python packaging and project management experience. Rye aims to be a “one-stop shop” for tasks like downloading Python versions, creating virtual environments, managing dependencies, linting and formatting.
ARMIN RONACHER

Starting Points for Contributing to Open Source With Python

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.
REAL PYTHON podcast

Data Science Workflows: Machine Learning Models with Python & Posit Connect

Via an end-to-end example, learn how data science organizations use Posit Connect as a platform for hosting internal machine learning models. This will give you a robust pattern for hosting and sharing models on Connect before you deploy them to a customer-facing system →
POSIT sponsor

Boring Python: Dependency Management

How to set up dependency management for Python projects in a “boring” way, meaning using standard, well-established tools to minimize surprises. It recommends using pip, virtualenv, and pip-tools to define dependencies, isolate environments, and track the full dependency tree.
JAMES BENNETT

Django Admin and Service Layer

If you need to perform operations on multiple Django objects, you might create service layer functions. The problem with this is the Django Admin is linked to the objects themselves. This post covers how to add custom calls to the Admin to invoke service layer functions.
ROMAN IMANKULOV

Python’s Format Mini-Language for Tidy Strings

In this tutorial, you’ll learn about Python’s format mini-language. See how to use it for creating working format specifiers and build nicely formatted strings and messages in your code.
REAL PYTHON

Python as a Configuration Language

“Conf is not a solved problem. While TOML, YAML, and JSON are popular choices…” the author often roles his own Python using Django-like modelling concepts. Read about how they do it.
BITE CODE

Python News: What’s New From January 2024

In January 2024, Python 3.13.0a3 was released. A new JIT compiler was added to Python 3.13. The Python Software Foundation announced new developers in residence, and the Python ecosystem released new versions of projects, such as Django and pandas.
REAL PYTHON

Discussions How to Deal With Constant Interruptions at Work?

HACKER NEWS

What Python Automation Scripts Do You Reuse Frequently?

HACKER NEWS

Articles & Tutorials Python Debugging Handbook

“Programming is an art, and bugs are an inevitable part of the creative process. Every developer encounters errors in their code – there’s really no exception to it. Because of this, understanding how to effectively debug is a crucial skill that can save you time and frustration.”
SAMYAK JAIN

Handling Unset Values in FastAPI With Pydantic

When using the HTTP PATCH method only those fields that got changed are updated. Pydantic sets fields not given as arguments as None so there is no way to distinguish between an explicit None value and an unset field. This post explains how you process this scenario.
ROMAN IMANKULOV

The Morning Paper for Hacker News Readers

Want a byte-sized version of Hacker News? Try TLDR’s free daily newsletter. TLDR covers the most interesting tech, science, and coding news in just 5 minutes. No sports, politics, or weather. Subscribe for free!
TLDR sponsor

Building Enumerations With Python’s enum

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 in the Python standard library.
REAL PYTHON course

What Are Python Raw Strings?

In this tutorial, you’ll learn the nuances of using raw string literals in your Python source code. Raw strings offer convenient syntax for including backslash characters in string literals without the complexity of escape sequences.
REAL PYTHON

Microdot: Yet Another Python Web Framework

Miguel is the maintainer of Microdot, a web framework for Python. This post covers why he wrote another Python web framework and what distinguishes Microdot from the crowd.
MIGUEL GRINBERG

Real Life Use of Decorators

Part 3 in a series on how Python decorators are used. This part covers real-life use cases including call interception, function registration, and behavioral enrichment.
BITE CODE

Add Vue to Your Django Templates With Vite

You don’t have to build a separate app to use Vue with Django. This article talks about the Vite tool and how you can integrate Vue.js directly into your templates.
ALICE

The Python Rust-Aissance

Companies like Polars are showing how with Rust, Python developers now have a better, smoother path towards building high-performance libraries.
SLATER STICH

Mutating the Immutable Tuple (Sort Of)

“Tuples are immutable, but their contents can change. Eh?! Let me tell you the story of my neighbours moving house, and all will make sense.”
STEPHEN GRUPETTA • Shared by Stephen Gruppetta

map() vs List Comprehensions

This tutorial covers the difference between Python’s map() and using list comprehensions, with examples on how to use both.
SOUMYA AGARWAL

Django, SQLite, and the Database Is Locked Error

This post explains “database is locked” errors in Django when using SQLite, and how to solve them.
ANZE

Using Python & Poetry Inside Docker

ASHISH BHATIA

Projects & Code apple-ocr: Apple Vision Wrapper for Text Extraction and Clustering

PYPI.ORG

RustPython: OSS CPython Written in Rust

RUSTPYTHON.GITHUB.IO

granian: Rust HTTP Server for Python Applications

GITHUB.COM/EMMETT-FRAMEWORK

django-webhook: Outgoing Webhooks Triggered on Model Changes

GITHUB.COM/DANIHODOVIC

Applio: Ultimate Voice Cloning Tool

GITHUB.COM/IAHISPANO

wafer: Web Application Firewall Fuzzing Tool

GITHUB.COM/SYSDIG

django-mock-queries: Mock Django Queryset Functions for Testing

GITHUB.COM/STPHIVOS

typed_configparser: Fully Typed INI/Config File Parser

GITHUB.COM/AJATKJ

tuttut: Converts a Midi File to ASCII Guitar Tabs

GITHUB.COM/NATECDR

Events Python Atlanta

February 9, 2024
MEETUP.COM

PyDelhi User Group Meetup

February 10, 2024
MEETUP.COM

DFW Pythoneers 2nd Saturday Teaching Meeting

February 10, 2024
MEETUP.COM

PiterPy Meetup

February 13, 2024
PITERPY.COM

Leipzig Python User Group Meeting

February 13, 2024
MEETUP.COM

IndyPy Monthly Meetup

February 14, 2024
MEETUP.COM

Happy Pythoning!
This was PyCoder’s Weekly Issue #615.
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

TechBeamers Python: Concat DataFrames in Pandas: A Step-by-Step Tutorial

Tue, 2024-02-06 13:02

In this tutorial, we’ll explore and demonstrate how to concat DataFrames in Pandas with different Python examples and use cases. If you usually work with data, merge datasets, or handle lots of info, learning the DataFrame concatenation technique in Pandas will be helpful. It makes your data analysis tasks a lot easier. Prerequisites Before we […]

The post Concat DataFrames in Pandas: A Step-by-Step Tutorial appeared first on TechBeamers.

Categories: FLOSS Project Planets

TechBeamers Python: How to Read Excel Files Using Pandas in Python

Tue, 2024-02-06 11:47

In this tutorial, we will explore how to read Excel files using the popular Python library, Pandas. Pandas is widely used for data manipulation and analysis, and it provides excellent support for handling Excel files. Whether you are working on a data analysis project, extracting data for machine learning, or simply need to read data […]

The post How to Read Excel Files Using Pandas in Python appeared first on TechBeamers.

Categories: FLOSS Project Planets

TechBeamers Python: How to Use Python To Generate Test Cases for Java Classes

Tue, 2024-02-06 10:49

In this HowTo tutorial, we’ll use Python to generate test cases for Java classes. For this purpose, Python provides an external module namely, javalang, so we’ll utilize it for test case generation. Since Python is much more user-friendly and easy to use than any other programming language, so why should we as a developer not […]

The post How to Use Python To Generate Test Cases for Java Classes appeared first on TechBeamers.

Categories: FLOSS Project Planets

Mike Driscoll: Creating a Modal Dialog For Your TUIs in Textual

Tue, 2024-02-06 10:24

Textual is a Python package that you can use to create beautiful text-based user interfaces (TUIs). In other words, you can create a GUI in your terminal with Textual.

In this tutorial, you will learn how to create a modal dialog in your terminal. Dialogs are great ways to alert the user about something or get some input. You also see dialogs used for such things as settings or help.

Let’s get started!

Adding a Modal Dialog

The first step is to think up some kind of application that needs a dialog. For this tutorial, you will create a form allowing the user to enter a name and address. Your application won’t save any data as that is outside the scope of this article, but it will demonstrate how to create the user interface and you can add that functionality yourself later on, if you wish.

To start, create a new file and name it something like tui_form.py. Then enter the following code:

from textual.app import App, ComposeResult from textual.containers import Center from textual.containers import Grid from textual.screen import ModalScreen from textual.widgets import Button, Footer, Header, Input, Static, Label class QuitScreen(ModalScreen): """Screen with a dialog to quit.""" def compose(self) -> ComposeResult: yield Grid( Label("Are you sure you want to quit?", id="question"), Button("Quit", variant="error", id="quit"), Button("Cancel", variant="primary", id="cancel"), id="dialog", ) def on_button_pressed(self, event: Button.Pressed) -> None: if event.button.id == "quit": self.app.exit() else: self.app.pop_screen() class Form(Static): def compose(self) -> ComposeResult: """ Creates the main UI elements """ yield Input(id="first_name", placeholder="First Name") yield Input(id="last_name", placeholder="Last Name") yield Input(id="address", placeholder="Address") yield Input(id="city", placeholder="City") yield Input(id="state", placeholder="State") yield Input(id="zip_code", placeholder="Zip Code") yield Input(id="email", placeholder="email") with Center(): yield Button("Save", id="save_button") class AddressBookApp(App): CSS_PATH = "modal.tcss" BINDINGS = [("q", "request_quit", "Quit")] def compose(self) -> ComposeResult: """ Lays out the main UI elemens plus a header and footer """ yield Header() yield Form() yield Footer() def action_request_quit(self) -> None: """Action to display the quit dialog.""" self.push_screen(QuitScreen()) if __name__ == "__main__": app = AddressBookApp() app.run()

Since this code is a little long, you will review it piece by piece. You will start at the bottom since the main entry point is the AddressBookApp class.

Here’s the code:

class AddressBookApp(App): CSS_PATH = "modal.tcss" BINDINGS = [("q", "request_quit", "Quit")] def compose(self) -> ComposeResult: """ Lays out the main UI elemens plus a header and footer """ yield Header() yield Form() yield Footer() def action_request_quit(self) -> None: """Action to display the quit dialog.""" self.push_screen(QuitScreen()) if __name__ == "__main__": app = AddressBookApp() app.run()

The AddressBookApp class is your application code. Here, you create a header, the form itself, and the footer of your application. When the user presses the q button, you also set up an accelerator key or key binding that calls action_request_quit(). This will cause your modal dialog to appear!

But before you look at that code, you should check out your Form’s code:

class Form(Static): def compose(self) -> ComposeResult: """ Creates the main UI elements """ yield Input(id="first_name", placeholder="First Name") yield Input(id="last_name", placeholder="Last Name") yield Input(id="address", placeholder="Address") yield Input(id="city", placeholder="City") yield Input(id="state", placeholder="State") yield Input(id="zip_code", placeholder="Zip Code") yield Input(id="email", placeholder="email") with Center(): yield Button("Save", id="save_button")

The Form class has a series of Input() widgets, which are text boxes, that you can enter your address information into. You specify a unique id for each widgets to give you a way to style each of them. You can read more about how that works in Using CSS to Style a Python TUI with Textual. The placeholder parameter lets you add a label to the text control so the user knows what should be entered in the widget.

Now you are ready to move on and look at your modal dialog code:

class QuitScreen(ModalScreen): """Screen with a dialog to quit.""" def compose(self) -> ComposeResult: yield Grid( Label("Are you sure you want to quit?", id="question"), Button("Quit", variant="error", id="quit"), Button("Cancel", variant="primary", id="cancel"), id="dialog", ) def on_button_pressed(self, event: Button.Pressed) -> None: if event.button.id == "quit": self.app.exit() else: self.app.pop_screen()

The QuitScreen class is made up of two functions:

  • compose() – Creates the widgets in the modal dialog
  • on_button_pressed() – The event handler that is fired when a button is pressed

The application will exit if the user presses the “Quit” button. Otherwise, the dialog will be dismissed, and you’ll return to your form screen.

You can style your application, including the modal dialog, using CSS. If you scroll back up to your application class, you’ll see that it refers to a CSS_PATH that points to a file named modal.tcss.

Here’s the CSS code that you’ll need to add to that file:

QuitScreen { align: center middle; } #dialog { grid-size: 2; grid-gutter: 1 2; grid-rows: 1fr 3; padding: 0 1; width: 60; height: 11; border: thick $background 80%; background: $surface; } #question { column-span: 2; height: 1fr; width: 1fr; content-align: center middle; } Button { width: 100%; }

This CSS will set the size and location of your modal dialog on the application. You tell Textual that you want the buttons to be centered and the dialog to be centered in the application.

To run your code, open up your terminal (or cmd.exe / Powershell on Windows), navigate to the folder that has your code in it, and run this command:

python tui_form.py

When you run this command, the initial screen will look like this:

To see the dialog, click the Save button to take the focus out of the text controls. Then hit the q button, and you will see the following:

You’ve done it! You created a modal dialog in your terminal!

Wrapping Up

Textual is a great Python package. You can create rich, expressive user interfaces in your terminal. These GUIs are also lightweight and can be run in your browser via Textual-web.

Want to learn more about Textual? Check out some of the following tutorials:

 

The post Creating a Modal Dialog For Your TUIs in Textual appeared first on Mouse Vs Python.

Categories: FLOSS Project Planets

Django Weblog: Django security releases issued: 5.0.2, 4.2.10, and 3.2.24

Tue, 2024-02-06 09:55

In accordance with our security release policy, the Django team is issuing Django 5.0.2, Django 4.2.10, and Django 3.2.24. These releases address the security issue detailed below. We encourage all users of Django to upgrade as soon as possible.

CVE-2024-24680: Potential denial-of-service in intcomma template filter

The intcomma template filter was subject to a potential denial-of-service attack when used with very long strings.

Affected supported versions
  • Django main branch
  • Django 5.0
  • Django 4.2
  • Django 3.2
Resolution

Patches to resolve the issue have been applied to Django's main branch and the 5.0, 4.2, and 3.2 stable branches. The patches may be obtained from the following changesets:

The following releases have been issued:

The PGP key ID used for this release is Natalia Bidart: 2EE82A8D9470983E

General notes regarding security reporting

As always, we ask that potential security issues be reported via private email to security@djangoproject.com, and not via Django's Trac instance, nor via the Django Forum, nor via the django-developers list. Please see our security policies for further information.

Categories: FLOSS Project Planets

Real Python: Python Basics Exercises: Lists and Tuples

Tue, 2024-02-06 09:00

In Python Basics: Lists and Tuples, you learned that Python lists 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 tuples, which are also collections of objects. However, while lists are mutable, tuples are immutable.

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.

In this video course, you’ll practice:

  • Defining and manipulating lists and tuples in Python
  • Leveraging the unique qualities of lists and tuples
  • Determining when you should use lists vs tuples

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.

This video course is part of the Python Basics series, which accompanies Python Basics: A Practical Introduction to Python 3. You can also check out the other Python Basics courses.

Note that you’ll be using IDLE to interact with Python throughout this course.

[ 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

Python Bytes: #370 Your Very Own Heroku

Tue, 2024-02-06 03:00
<strong>Topics covered in this episode:</strong><br> <ul> <li><a href="https://dokku.com"><strong>Dokku</strong></a></li> <li><a href="https://www.nicholashairs.com/posts/major-changes-between-python-versions/"><strong>Summary of Major Changes Between Python Versions</strong></a></li> <li>How to check Internet Speed via Terminal? <a href="https://github.com/sivel/speedtest-cli">speedtest-cli</a></li> <li><strong>Blogs: We all should blog more</strong></li> <li><strong>Extras</strong></li> <li><strong>Joke</strong></li> </ul><a href='https://www.youtube.com/watch?v=1P-XjiHzSNU' style='font-weight: bold;'data-umami-event="Livestream-Past" data-umami-event-episode="370">Watch on YouTube</a><br> <p><strong>About the show</strong></p> <p>Sponsored by us! Support our work through:</p> <ul> <li>Our <a href="https://training.talkpython.fm/"><strong>courses at Talk Python Training</strong></a></li> <li><a href="https://courses.pythontest.com/p/the-complete-pytest-course"><strong>The Complete pytest Course</strong></a></li> <li><a href="https://www.patreon.com/pythonbytes"><strong>Patreon Supporters</strong></a></li> </ul> <p><strong>Connect with the hosts</strong></p> <ul> <li>Michael: <a href="https://fosstodon.org/@mkennedy"><strong>@mkennedy@fosstodon.org</strong></a></li> <li>Brian: <a href="https://fosstodon.org/@brianokken"><strong>@brianokken@fosstodon.org</strong></a></li> <li>Show: <a href="https://fosstodon.org/@pythonbytes"><strong>@pythonbytes@fosstodon.org</strong></a></li> </ul> <p>Join us on YouTube at <a href="https://pythonbytes.fm/stream/live"><strong>pythonbytes.fm/live</strong></a> to be part of the audience. Usually Tuesdays at 11am PT. Older video versions available there too.</p> <p><strong>Michael #1:</strong> <a href="https://dokku.com"><strong>Dokku</strong></a></p> <ul> <li>An open source PAAS alternative to Heroku.</li> <li>Dokku helps you build and manage the lifecycle of applications from building to scaling.</li> <li>Powered by Docker, you can install Dokku on any hardware.</li> <li>Once it's set up on a host, you can push Heroku-compatible applications to it via Git. </li> <li>Rich <a href="https://dokku.com/docs/community/plugins/">plug in architecture</a>.</li> </ul> <p><strong>Brian #2:</strong> <a href="https://www.nicholashairs.com/posts/major-changes-between-python-versions/"><strong>Summary of Major Changes Between Python Versions</strong></a></p> <ul> <li>Nicholas Hairs</li> <li>Changes between versions &amp; Tools &amp; utilities to help with switching</li> <li>Hopefully you’re already at least at 3.8, but come on, 3.11 &amp; 3.12 are so fun!</li> <li>Useful things <ul> <li><code>pyupgrade</code> can automatically upgrade code base <ul> <li>(However, I frequently just upgrade and run tests and let my old code be as-is until it bugs me. - Brian)</li> </ul></li> <li><code>black</code> checks <code>pyproject.toml</code> <code>requires-python</code> setting and uses version specific rules.</li> </ul></li> <li>Versions (way more highlights listed in the article) <ul> <li>3.8 <ul> <li>Assignment expressions <code>:=</code> walrus</li> <li><code>f"{variable=}"</code> now works</li> </ul></li> <li>3.9 <ul> <li>Typing has built in generics like <code>dict[]</code>, so no more <code>from typing import Dict</code></li> <li>Dict union operator</li> <li>Strings can <code>removeprefix</code> and <code>removesuffix</code></li> </ul></li> <li>3.10 <ul> <li>Structural pattern matching <code>match/case</code></li> <li>Typing: Union using pipe <code>|</code></li> <li>Dataclasses support <code>slots=True</code> and <code>kw_only=True</code></li> </ul></li> <li>3.11 <ul> <li><code>tomllib</code> included as a standard TOMP parser</li> <li>Exception groups</li> <li>Exception Notes <code>add_note()</code></li> <li>Typing: A <code>Self</code> type</li> <li>Star unpacking expressions allowed in <code>for</code> statements: <code>for x in *a, *b:</code></li> </ul></li> <li>3.12 <ul> <li>f-strings can re-use quotes</li> <li>Typing: better type parameter syntax</li> <li>Typing: <code>@override</code> decorator ensures a method being overridden by a child class actually exists.</li> </ul></li> </ul></li> </ul> <p><strong>Michael #3:</strong> How to check Internet Speed via Terminal? <a href="https://github.com/sivel/speedtest-cli">speedtest-cli</a></p> <ul> <li>Command line interface for testing internet bandwidth using speedtest.net</li> <li>Just <code>pipx install speedtest-cli</code></li> <li>Has a <a href="https://github.com/sivel/speedtest-cli/wiki">Python API</a> too</li> </ul> <p><strong>Brian #4:</strong> <strong>Blogs: We all should blog more</strong></p> <ul> <li>Jeff Triplett is attempting one post per day in February <ul> <li>Feb 1: <a href="https://micro.webology.dev/2024/02/01/choosing-the-right.html">Choosing the Right Python and Django Versions for Your Projects</a></li> <li>Feb 2: <a href="https://micro.webology.dev/2024/02/02/my-first-mac.html">My First Mac</a> <ul> <li>Which also links to a quite interesting Personal: <a href="https://jefftriplett.com/2023/default-apps-2023/">Default Apps 2023</a></li> </ul></li> <li>Feb 3: <a href="https://micro.webology.dev/2024/02/03/whats-your-goto.html">What’s Your Go-to Comfort Media? [rough cut]</a></li> <li>Feb 4: <a href="https://micro.webology.dev/2024/02/04/the-django-apps.html">The Django apps I actually use (rough cut)</a></li> <li>Feb 5: <a href="https://micro.webology.dev/2024/02/05/how-to-test.html">How to test with Django and pytest fixtures</a></li> </ul></li> <li>Need ideas? <ul> <li>Check out <a href="https://hamatti.org/posts/build-an-idea-bank-and-never-run-out-of-blog-ideas/">Build an idea bank and never run out of blog ideas</a></li> </ul></li> <li>Not using AI? Thanks. We appreciate that. <ul> <li>Maybe tag it as <a href="https://notbyai.fyi/">Not By AI</a></li> </ul></li> </ul> <p><strong>Extras</strong> </p> <p>Brian:</p> <ul> <li>If upgrading to pytest 8, be aware that running individual tests with parametrization will result in a reverse order. <ul> <li>It shouldn’t matter. <a href="https://podcast.pythontest.com/episodes/211-stamp-out-test-dependencies-with-pytest-plugins">You shouldn’t be depending on test order.</a></li> <li>But it was surprising to me.</li> <li><a href="https://github.com/pytest-dev/pytest/issues/11937">Issue has been logged</a></li> </ul></li> </ul> <p>Michael:</p> <ul> <li><a href="https://orbstack.dev">Orbstack</a> follow up</li> </ul> <p><strong>Joke:</strong> <a href="https://workchronicles.com/white-lies/">White Lies</a></p>
Categories: FLOSS Project Planets

Glyph Lefkowitz: Let Me Tell You A Secret

Mon, 2024-02-05 17:36

I do consulting1 on software architecture, network protocol development, python software infrastructure, streamlined cloud deployment, and open source strategy, among other nerdy things. I enjoy solving challenging, complex technical problems or contributing to the open source commons. On the best jobs, I get to do both.

Today I would like to share with you a secret of the software technology consulting trade.

I should note that this secret is not specific to me. I have several colleagues who have also done software consulting and have reflected versions of this experience back to me.2

We’ll get to the secret itself in a moment, but first, some background.

Companies do not go looking for consulting when things are going great. This is particularly true when looking for high-level consulting on things like system architecture or strategy. Almost by definition, there’s a problem that I have been brought in to solve. Ideally, that problem is a technical challenge.

In the software industry, your team probably already has some software professionals with a variety of technical skills, and thus they know what to do with technical challenges. Which means that, as often as not, the problem is to do with people rather than technology, even it appears otherwise.

When you hire a staff-level professional like myself to address your software team’s general problems, that consultant will need to gather some information. If I am that consultant and I start to suspect that the purported technology problem that you’ve got is in fact a people problem, here is what I am going to do.

I am going to go get a pen and a pad of paper, then schedule a 90-minute meeting with the most senior IC3 engineer that you have on your team. I will bring that pen and paper to the meeting. I will then ask one question:

What is fucked up about this place?

I will then write down their response in as much detail as I can manage. If I have begun to suspect that this meeting is necessary, 90 minutes is typically not enough time, and I will struggle to keep up. Even so, I will usually manage to capture the highlights.

One week later, I will schedule a meeting with executive leadership, and during that meeting, I will read back a very lightly edited4 version of the transcript of the previous meeting. This is then routinely praised as a keen strategic insight.

I should pause here to explicitly note that — obviously, I hope — this is not an oblique reference to any current or even recent client; if I’d had this meeting recently it would be pretty awkward to answer that “so, I read your blog…” email.5 But talking about clients in this way, no matter how obfuscated and vague the description, is always a bit professionally risky. So why risk it?

The thing is, I’m not a people manager. While I can do this kind of work, and I do not begrudge doing it if it is the thing that needs doing, I find it stressful and unfulfilling. I am a technology guy, not a people person. This is generally true of people who elect to go into technology consulting; we know where the management track is, and we didn’t pick it.

If you are going to hire me for my highly specialized technical expertise, I want you to get the maximum value out of it. I know my value; my rates are not low, and I do not want clients to come away with the sense that I only had a couple of “obvious” meetings.

So the intended audience for this piece is potential clients, leaders of teams (or organizations, or companies) who have a general technology problem and are wondering if they need a consultant with my skill-set to help them fix it. Before you decide that your issue is the need to implement a complex distributed system consensus algorithm, check if that is really what’s at issue. Talk to your ICs, and — taking care to make sure they understand that you want honest feedback and that they are safe to offer it — ask them what problems your organization has.

During this meeting it is important to only listen. Especially if you’re at a small company and you are regularly involved in the day-to-day operations, you might feel immediately defensive. Sit with that feeling, and process it later. Don’t unload your emotional state on an employee you have power over.6

“Only listening” doesn’t exclusively mean “don’t push back”. You also shouldn’t be committing to fixing anything. While the information you are gathering in these meetings is extremely valuable, and you should probably act on more of it than you will initially want to, your ICs won’t have the full picture. They really may not understand why certain priorities are set the way they are. You’ll need to take that as feedback for improving internal comms rather than “fixing” the perceived problem, and you certainly don’t want to make empty promises.

If you have these conversations directly, you can get something from it that no consultant can offer you: credibility. If you can actively listen, the conversation alone can improve morale. People like having their concerns heard. If, better still, you manage to make meaningful changes to address the concerns you’ve heard about, you can inspire true respect.

As a consultant, I’m going to be seen as some random guy wasting their time with a meeting. Even if you make the changes I recommend, it won’t resonate the same way as someone remembering that they personally told you what was wrong, and you took it seriously and fixed it.

Once you know what the problems are with your organization, and you’ve got solid technical understanding that you really do need that event-driven distributed systems consensus algorithm implemented using Twisted, I’m absolutely your guy. Feel free to get in touch.

  1. While I immensely value my patrons and am eternally grateful for their support, at — as of this writing — less than $100 per month it doesn’t exactly pay the SF bay area cost-of-living bill. 

  2. When I reached out for feedback on a draft of this essay, every other consultant I showed it to said that something similar had happened to them within the last month, all with different clients in different sectors of the industry. I really cannot stress how common it is. 

  3. “individual contributor”, if this bit of jargon isn’t universal in your corner of the world; i.e.: “not a manager”. 

  4. Mostly, I need to remove a bunch of profanity, but sometimes I will also need to have another interview, usually with a more junior person on the team to confirm that I’m not relaying only a single person’s perspective. It is pretty rare that the top-of-mind problems are specific to one individual, though. 

  5. To the extent that this is about anything saliently recent, I am perhaps grumbling about how tech CEOs aren’t taking morale problems generated by the constant drumbeat of layoffs seriously enough

  6. I am not always in the role of a consultant. At various points in my career, I have also been a leader needing to sit in this particular chair, and believe me, I know it sucks. This would not be a common problem if there weren’t a common reason that leaders tend to avoid this kind of meeting. 

Categories: FLOSS Project Planets

TestDriven.io: Django REST Framework and Vue versus Django and HTMX

Mon, 2024-02-05 17:28
This article compares the development experience with Vue and Django REST Framework against HTMX and Django.
Categories: FLOSS Project Planets

PyCharm: PyCharm 2024.1 EAP 3: Tool Window Names in the New UI

Mon, 2024-02-05 17:05

PyCharm 2024.1 EAP 3 is now available. This latest update focuses on enhancing your interactions with the IDE’s interface.

You can download the new version from our website, update directly from the IDE or via the free Toolbox App, or use snaps for Ubuntu.

Let’s take a closer look at what’s included in this new version.

User experience Option to show tool window names in the side toolbars

Starting with PyCharm 2024.1 EAP 3, it is now possible to display tool window names on side toolbars in the new UI. Simply right-click on the toolbar to access the context menu and choose Show Tool Window Names, or enable this option via Settings / Preferences | Appearance & Behavior | Appearance | Tool Windows. It’s also possible to tailor the width of the toolbar by dragging its edge.

Git tab removed from the Search Everywhere dialog

After analyzing the usage statistics, we’ve removed the Git tab from the Search Everywhere dialog by default. If you want to bring it back, you can do so via the Show Git tab in Search Everywhere checkbox in Settings / Preferences | Advanced Settings | Version Control. Git.

That’s it for this week. For a full list of changes, please refer to the release notes.

We value your feedback on these new updates and features. Feel free to leave your thoughts in the comments section or via X (formerly Twitter). If you encounter any issues, please don’t hesitate to report them via our issue tracker.

Categories: FLOSS Project Planets

EuroPython: Seize the Opportunity: EuroPython 2024 Call for Contributors Extended!

Mon, 2024-02-05 13:28

Dear Python Enthusiasts,

Excitement is in the air as we gear up for EuroPython 2024, the conference that brings together the brightest minds in the European Python community!

In the spirit of inclusivity and community collaboration, we are thrilled to announce an extension of the Call for Contributors for EuroPython 2024! We want to ensure that everyone who wishes to contribute has the opportunity to do so. This extension allows more Pythonistas to be a part of this incredible event, shaping the conference and making it an enriching experience for all.

How Can You Get Involved?1. Review the proposals:

Have you navigated the ins and outs of proposal submissions? The heart of EuroPython lies in its program. If you&aposre passionate about curating an exceptional conference agenda, we welcome you to join our team of Reviewers. By reviewing proposals and assisting in the selection process, you&aposll contribute to crafting a lineup that reflects the diversity and innovation within the Python community.

2. Volunteer for the Conference Organisation:

EuroPython is not just about talks; it&aposs about fostering connections and creating memorable experiences. We&aposre looking for volunteers to help with various aspects of the conference, from registration to technical support. Your contribution, big or small, will play a crucial role in making EuroPython 2024 an unforgettable event for everyone involved.

3. Become a Speaker Mentor:

Do you have experience as a speaker at Python conferences? Are you passionate about mentorship? We invite you to be a guiding force for our aspiring speakers. By volunteering as a Speaker Mentor, you&aposll play a pivotal role in shaping the future of Python conference speakers. Your expertise will help potential speakers refine their proposals, ensuring a diverse and high-quality program.

How to Get Involved:

1. Reviewers:

  • Sign up on the Registration Form.
  • Share insights into your experience with Python and conferences.
  • Join our collaborative effort to shape an outstanding conference program.

2. Volunteer for Conference Organisation:

  • If you’d like to learn more about how we work, check this link: Teams Descriptions
  • Let us know your availability and preferences for volunteering roles.
  • Be a crucial part of the behind-the-scenes magic that makes EuroPython memorable.

3. Speaker Mentorship:

  • Please fill out the Speaker Mentor Application Form.
  • Provide details about your experience and areas of expertise.
  • Our team will match you with potential speakers based on your background.
&#x1F4DD; Make sure to sign up by February 12th 2024 AoE! &#x1F4DD;

Why Volunteer?

Community Contribution:

  • Contribute to the Python community by sharing your knowledge and experience.
  • Help newcomers find their voice in the tech world.

Networking Opportunities:

  • Connect with like-minded individuals, speakers, and fellow volunteers.
  • Build relationships that can shape your professional journey.

Personal Growth:

  • Hone your mentoring and organisational skills.
  • Gain insights into the latest trends and innovations in the Python ecosystem.

Don&apost miss this chance to be an integral part of EuroPython 2024! Let&aposs join forces to make this conference a celebration of Python&aposs diversity, innovation, and community spirit. Together, we can create an event that inspires, educates, and leaves a lasting impact on every participant.

See you at EuroPython 2024!


EuroPython 2024 Organizing Team

Categories: FLOSS Project Planets

Python Morsels: TextIOWrapper‽ converting files to strings in Python

Mon, 2024-02-05 11:00

Every encountered an _io.TextIOWrapper object when you wished you had a string? That's Python's version of a "text file" object!

Table of contents

  1. TextIOWrapper objects are files
  2. _io.TextIOWrapper aren't the only "files"
  3. Don't try to pass a file to str
  4. You can also read line-by-line
  5. Use read to convert _io.TextIOWrapper objects to strings

TextIOWrapper objects are files

If you use Python's built-in open function to read from a file, you'll end up with a _io.TextIOWrapper object. You can think of this as a file object.

>>> file = open("example.txt", mode="rt") >>> type(file) <class '_io.TextIOWrapper'>

If you open a file in read mode (the default mode), you should be able to call the read method on your file object to read your file into a string:

>>> contents = file.read() >>> contents 'This is an example text-based file.\nIt existed before we read it.\n'

More on reading text files in reading files in Python.

_io.TextIOWrapper aren't the only "files"

Due to duck typing, …

Read the full article: https://www.pythonmorsels.com/TextIOWrapper/
Categories: FLOSS Project Planets

Real Python: Python News: What's New From January 2024

Mon, 2024-02-05 09:00

In January 2024, Python 3.13.0a3 was released! With several exciting features, improvements, and optimizations, this release is the third of six planned alpha releases. During the alpha phase, features may be added up until the start of the beta phase on May 7. This is a pre-release, and you shouldn’t use it for production environments. However, it’s a great way to try out some new and exciting language features.

The steering council had its elections last December, and the Python Software Foundation made a few cool announcements, including the announcement of a new developer in residence.

There is also exciting news regarding Python conferences, such as PyCon US 2024 and DjangoCon Europe 2024.

Let’s dive into the most exciting Python news from January 2024!

Python 3.13.0 Alpha 3 Arrives

This January, Python released its third alpha preview release, 3.13.0a3. This version is the third of six planned alpha releases. During the alpha phase, Python will receive new features up until the start of the beta phase on May 7. Alpha releases make it easier to test the current state of new features and bug fixes and to test the release process.

Many new features for Python 3.13 are still being planned. The primary efforts surround two core areas:

  • Removing the global interpreter lock, or GIL (PEP 703)
  • Improving Python performance

So far, some of the most notable changes include the following:

  • Colorized exception tracebacks by default in the REPL
  • Stripped leading indentation in docstrings, which reduces memory use and the size of .pyc files
  • Scheduled removals of deprecated modules: aifc, audioop, chunk, cgi, cgitb, crypt, imghdr, mailcap, msilib, nis, nntplib, ossaudiodev, pipes, sndhdr, spwd, sunau, telnetlib, uu, xdrlib, and lib2to3 (PEP 594)
  • Many other removals of deprecated classes, functions, and methods in various standard-library modules

As usual, this version also brings several deprecations that you may need to consider. For a detailed list of changes, additions, and removals, you can check the changelog. The next pre-release of Python 3.13 will be 3.13.0a4, which is currently scheduled for February 13.

JIT (Just-in-Time) Compiler Available on Python 3.13

In late December 2023, CPython core developer Brandt Bucher pushed a pull request to the Python 3.13 branch adding a JIT (just-in-time) compiler. This pull request responds to issue #113464 JIT Compilation, which is intended to add just-in-time compilation to CPython 3.13.0.

JIT compilation consists of compiling the code during the execution of a program rather than before execution. It’s an on-demand compilation.

Real Python contributor Anthony Shaw has written a great post about this new JIT compiler in Python 3.13. In his article, he talks about JIT compilers and different types of them.

The most exciting result of having this JIT compiler in Python 3.13 is that initial benchmarks show that Python’s performance will improve by 2 to 9 percent! This may seem like a small improvement, but as Anthony Shaw says:

Think of this JIT as being the cornerstone of a series of much larger optimizations. None of which are possible without it. (Source)

Read the full article at https://realpython.com/python-news-january-2024/ »

[ 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

Python GUIs: QLineEdit — A Simple Text Input Widget

Mon, 2024-02-05 01:00

The QLineEdit class is a versatile tool for single-line text input. The widget facilitates text manipulation by supporting insertion, deletion, selection, and cut-copy-paste operations natively. You can use line edits when you need to accept text input from your users in a PyQt/PySide application.

The widget is highly customizable. You can set it up to include placeholder text, input masks, input validators, and more. It also supports many keyboard shortcuts out of the box and is able to process custom ones. This feature opens an opportunity to enhance user input speed and efficiency.

In this article, you will learn the basics of using QLineEdit by going through its most commonly used features and capabilities.

Table of Contents Creating Line Edit Widgets With QLineEdit

A line edit allows the user to enter and edit a single line of plain text with a useful collection of editing functionalities, such as insertion, deletion, selection, cut-copy-paste, and drag-and-drop operations.

If you've used PyQt or PySide to create GUI applications in Python, then it'd be likely that you already know about the QLineEdit class. This class allows you to create line edits in your graphical interfaces (GUI) quickly.

The QLineEidt class provides two different constructors that you can use to create line edits according to your needs:

Constructor Description QLineEdit(parent: QWidget = None) Constructs a line edit with a parent widget but without text QLineEdit(text: str, parent: QWidget = None) Constructs a line edit with default text and a parent widget

The parent widget would be the window or dialog where you need to place the line edit. The text can be a default text that will appear in the line edit when you run the application.

To illustrate how to use the above constructors, we can code a demo example:

python from PyQt6.QtWidgets import QApplication, QLineEdit, QVBoxLayout, QWidget class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("QLineEdit Constructors") self.resize(300, 100) # Line edit with a parent widget top_line_edit = QLineEdit(parent=self) # Line edit with a parent widget and a default text bottom_line_edit = QLineEdit( "Hello! This is a line edit.", parent=self ) layout = QVBoxLayout() layout.addWidget(top_line_edit) layout.addWidget(bottom_line_edit) self.setLayout(layout) app = QApplication([]) window = Window() window.show() app.exec()

In this example, we first do the required imports and then define the Window class inheriting from QWidget. Inside Window, we create two QLineEdit widgets.

To create the first line edit, we use the first constructor of QLineEdit, passing only a parent widget. For the second line editor, we use the second constructor, which requires the parent widget and a default text. Note that the text is a regular Python string.

Save the code to a file called constructors.py file and run it from your command line. You'll get a window that looks something like this:

Standard window showing our two line edits.

The first line edit has no text. In most cases, this is how you would create your line edits because they're designed for accepting input. If you'd like to just display some text, then you can use a QLabel widget instead. The second line edit displays the text that you passed to the constructor.

Both line edits are ready for accepting input text. Note that you can use all the following keyboard shortcuts to optimize your text input process:

Keys Action Left Arrow Moves the cursor one character to the left Shift+Left Arrow Moves and selects text one character to the left Right Arrow Moves the cursor one character to the right Shift+Right Arrow Moves and selects text one character to the right Home Moves the cursor to the beginning of the line End Moves the cursor to the end of the line Backspace Deletes the character to the left of the cursor Ctrl+Backspace Deletes the word to the left of the cursor Delete Deletes the character to the right of the cursor Ctrl+Delete Deletes the word to the right of the cursor Ctrl+A Select all Ctrl+C Copies the selected text to the clipboard Ctrl+Insert Copies the selected text to the clipboard Ctrl+K Deletes to the end of the line Ctrl+V Pastes the clipboard text into the line edit Shift+Insert Pastes the clipboard text into the line edit Ctrl+X Deletes the selected text and copies it to the clipboard Shift+Delete Deletes the selected text and copies it to the clipboard Ctrl+Z Undoes the last operation Ctrl+Y Redoes the last undone operation

That's a lot of shortcuts! This table is just a sample of all the features that the QLineEdit class provides out of the box.

In addition to these keyboard shortcuts, the QLineEdit class provides a context menu that you can trigger by clicking on a line edit using the right button of your mouse:

QLineEdit with a context menu visible.

The built-in context menu provides basic edition options, such as cut, copy, paste, and delete. It also has options for undoing and redoing edits, and for selecting all the content of a given line edit.

Creating Non-Editable Line Edits

Sometimes, we need to make a line edit non-editable. By default, all line edits are editable because their main use case is to provide text input for the user. However, in some situations, a non-editable line edit can be useful.

For example, say that you're creating a GUI application that generates some recovery keys for the users. The user must be able to copy the key to a safe place so that they can use it to recover access if they forget their password. In this situation, creating a non-editable line edit can provide a suitable solution.

To make a line edit read-only, we can use the readOnly property and its setter method setReadOnly() as in the following example:

python import secrets from PyQt6.QtWidgets import ( QApplication, QLabel, QLineEdit, QVBoxLayout, QWidget, ) class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Non-editable QLineEdit") self.resize(300, 100) non_editable_line_edit = QLineEdit(parent=self) non_editable_line_edit.setReadOnly(True) non_editable_line_edit.setText(secrets.token_hex(16)) layout = QVBoxLayout() layout.addWidget(QLabel(parent=self, text="Your secret key:")) layout.addWidget(non_editable_line_edit) self.setLayout(layout) app = QApplication([]) window = Window() window.show() app.exec()

In this example, we create a non-editable line edit by using the setReadOnly() method. When we set the readOnly property to True, our line edit won't accept editions. It'll only allow us to select and copy its content.

Go ahead and run the application from your command line to explore how this line edit works. You'll get a window like the following:

A read-only line edit with editing disabled.

If you play a bit with this line edit, you'll soon discover that you can't change its text. You'll also note that the options in the context menu are now limited to Copy and Select All.

Creating Line Edits for Passwords

Another cool feature of the QLineEdit class is that it allows you to create text input for passwords. This can be pretty convenient for those applications that manage several users, and each user needs to have access credentials.

You can create line edits for passwords by using the echoMode() method. This method takes one of the following constants as an argument:

Constant Value Description QLineEdit.EchoMode.Normal 0 Display characters as you enter them. QLineEdit.EchoMode.NoEcho 1 Display no characters when you enter them. QLineEdit.EchoMode.Password 2 Display platform-dependent password mask characters instead of the characters you enter. QLineEdit.EchoMode.PasswordEchoOnEdit 3 Display characters as you enter them while editing. Display characters as the Password mode does when reading.

The Normal mode is the default. The NoEcho mode may be appropriate for critical passwords where even the length of the password should be kept secret. The Password mode is appropriate for most password use cases, however PasswordEchoOnEdit can be used instead if you need to give users some confirmation of what they are typing.

Here's a sample app that shows a user and password form:

python from PyQt6.QtWidgets import ( QApplication, QFormLayout, QLineEdit, QWidget, ) class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Password QLineEdit") self.resize(300, 100) username_line_edit = QLineEdit(parent=self) password_line_edit = QLineEdit(parent=self) password_line_edit.setEchoMode(QLineEdit.EchoMode.Password) layout = QFormLayout() layout.addRow("Username:", username_line_edit) layout.addRow("Password:", password_line_edit) self.setLayout(layout) app = QApplication([]) window = Window() window.show() app.exec()

In this example, you call setEchoMode() on the password_line_edit widget using the Password mode as an argument. When you run this code from your command line, you get the following window on your screen:

Window with a username and password line edit.

The username_line_edit line edit is in Normal mode, so we can see the characters as we type them in. In contrast, the Password line edit is in Password mode. In this case, when we enter a character, the line edit shows the platform's character for passwords.

Manipulating the Input in a Line Edit

You can change the text of a line edit using the setText() or insert() methods. You can retrieve the text with the text() method. However, these are not the only operations that you can perform with the text of a line edit.

The following table shows a summary of some of the most commonly used methods for text manipulation in line edits:

Method Description setText(text) Sets the text of a line edit to text, clears the selection, clears the undo/redo history, moves the cursor to the end of the line, and resets the modified property to false. insert(text) Deletes any selected text, inserts text, and validates the result. If it is valid, it sets it as the new contents of the line edit. clear() Clears the contents of the line edit. copy() Copies the selected text to the clipboard. cut() Copies the selected text to the clipboard and deletes it from the line edit. paste() Inserts the clipboard's text at the cursor position, deleting any selected text. redo() Redoes the last operation if redo is available. Redo becomes available once the user has performed one or more undo operations on text in the line edit. undo() Undoes the last operation if undo is available. Undo becomes available once the user has modified the text in the line edit. selectAll() Selects all the text and moves the cursor to the end.

You can use any of these methods to manipulate the text of a line edit from your code. Consider the following example where you have two line edits and two buttons that take advantage of some of the above methods to copy some text from one line edit to the other:

python from PyQt6.QtWidgets import ( QApplication, QGridLayout, QLabel, QLineEdit, QPushButton, QWidget, ) class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Copy and Paste") self.resize(300, 100) self.source_line_edit = QLineEdit(parent=self) self.source_line_edit.setText("Hello, World!") self.dest_line_edit = QLineEdit(parent=self) copy_button = QPushButton(parent=self, text="Copy") paste_button = QPushButton(parent=self, text="Paste") copy_button.clicked.connect(self.copy) paste_button.clicked.connect(self.paste) layout = QGridLayout() layout.addWidget(self.source_line_edit, 0, 0) layout.addWidget(copy_button, 0, 1) layout.addWidget(self.dest_line_edit, 1, 0) layout.addWidget(paste_button, 1, 1) self.setLayout(layout) def copy(self): self.source_line_edit.selectAll() self.source_line_edit.copy() def paste(self): self.dest_line_edit.clear() self.dest_line_edit.paste() app = QApplication([]) window = Window() window.show() app.exec()

In this example, we create two line edits. The first one will hold some sample text. The second line edit will receive the text. Then, we create two buttons and connect their clicked signals to the copy() and paste() slots.

Inside the copy() method we first select all the text from the source line edit. Then we use the copy() method to copy the selected text to the clipboard. In paste(), we call clear() on the destination line edit to remove any previous text. Then, we use the paste() method to copy the clipboard's content.

Go ahead and run the application. You'll get the following window on your screen:

QLineEdit with Copy & Paste buttons attached to handlers.

Once you've run the app, then you can click the Copy button to copy the text in the first line edit. Next, you can click the Paste button to paste the copied text to the second line edit. Go ahead and give it a try!

Aligning and Formatting the Text in a Line Edit

You can also align and format the text in a line edit. For example, for text alignment, you can use the setAlignment() method with one or more alignment flags. Some of the most useful flags that you can find in the Qt.AlignmentFlag namespace includes the following:

Flag Description AlignLeft Aligns with the left edge. AlignRight Aligns with the right edge. AlignHCenter Centers horizontally in the available space. AlignJustify Justifies the text in the available space. AlignTop Aligns with the top. AlignBottom Aligns with the bottom. AlignVCenter Centers vertically in the available space. AlignCenter Centers in both dimensions.

If you want to apply multiple alignment flags to a given line edit, you don't have to call setAlignment() multiple times. You can just use the bitwise OR operator (|) to combine them. Consider the following example:

python from PyQt6.QtCore import Qt from PyQt6.QtWidgets import QApplication, QLineEdit class Window(QLineEdit): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Aligning Text") self.resize(300, 100) self.setText("Hello, World!") self.setAlignment(Qt.AlignmentFlag.AlignCenter) app = QApplication([]) window = Window() window.show() app.exec()

In this example, we use a QLineEdit as the only component of our app's GUI. Using the setAlignment() method, we center the "Hello, World!" message in both directions, horizontally and vertically. To do this, we use the AlignCenter flag. Here's what the app looks like:

QLineEdit with text alignment set.

Go ahead and play with other flags to see their effect on the text alignment. Use the | bitwise operator to combine several alignment flags.

Line edits also have a textMargins property that you can tweak to customize the text alignment using specific values. To set margin values for your text, you can use the setTextMargins() method, which has the following signatures:

Method Description setTextMargins(left, top, right, bottom) Sets the margins around the text to have the sizes left, top, right, and bottom. setTextMargins(margins) Sets the margins around the text using a QMargins object.

The first signature allows you to provide four integer values as the left, top, right, and bottom margins for the text. The second signature accepts a QMargins object as an argument. To build this object, you can use four integer values with the same meaning as the left, top, right, and bottom arguments in the first signature.

Here's an example of how to set custom margins for the text in a line edit:

python from PyQt6.QtWidgets import QApplication, QLineEdit class Window(QLineEdit): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Aligning Text") self.resize(300, 100) self.setText("Hello, World!") self.setTextMargins(30, 30, 0, 0) app = QApplication([]) window = Window() window.show() app.exec()

In this example, you set the left and top margins to custom values. Here's how this app looks when you run it:

QLineEdit with text margins added.

Using the setTextMargins() method, we can place the text in the desired place in a line edit, which may be a requirement in some situations.

Connecting Signals and Slots

When you're creating a GUI application and you need to use line edits, you may need to perform actions when the user enters or modifies the content of the line edit. To do this, you need to connect some of the signals of the line edit to specific slots or functions.

Depending on specific user events, the QLineEdit class can emit several different signals. Here's is a summary of these signals and their corresponding meaning:

Signal Emitted textChanged(text) Whenever the user changes the text either manually or programmatically. The text argument is the new text. textEdited(text) Whenever the user edits the text manually. The text argument is the new text. editingFinished When the user presses the Return or Enter key, or when the line edit loses focus, and its contents have changed since the last time this signal was emitted. inputRejected When the user presses a key that is an unacceptable input. returnPressed When the user presses the Return or Enter key. selectionChanged When the selection changes.

We can connect either of these signals with any slot. A slot is a method or function that performs a concrete action in your application. We can connect a signal and a slot so that the slot gets called when the signal gets emitted. Here's the required syntax to do this:

python line_edit.<signal>.connect(<method>)

In this construct, line_edit is the QLineEdit object that we need to connect with a given slot. The <signal> placeholder can be any of the abovementioned signals. Finally, <method> represents the target slot or method.

Let's write an example that puts this syntax into action. For this example, we'll connect the textEdited signal with a method that updates the text of a QLabel to match the text of our line edit:

python from PyQt6.QtWidgets import ( QApplication, QLabel, QLineEdit, QVBoxLayout, QWidget, ) class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Signal and Slot") self.resize(300, 100) self.line_edit = QLineEdit(parent=self) self.label = QLabel(parent=self) self.line_edit.textEdited.connect(self.update_label) layout = QVBoxLayout() layout.addWidget(self.line_edit) layout.addWidget(self.label) self.setLayout(layout) def update_label(self): self.label.setText(self.line_edit.text()) app = QApplication([]) window = Window() window.show() app.exec()

In this example, we connect the line edit's textEdited signal with the update_label() method, which sets the label's text to match the text we enter in our line edit. Go ahead and run the app. Then, enter some text in the line edit and see what happens with the label at the bottom of the app's window.

Validating Input in Line Edits

We can provide input validators to our line edits using the setValidator() method. This method takes a QValidator object as an argument. PyQt has a few built-in validators that you can use directly on a line edit:

Validator objects process the input to check whether it's valid. In general, validator object has three possible states:

Constant Value Description QValidator.State.Invalid 0 The input is invalid. QValidator.State.Intermediate 1 The input is a valid intermediate value. QValidator.State.Acceptable 2 The input is acceptable as a final result.

When you set a validator to a given line edit, the user may change the content to any Intermediate value during editing. However, they can't edit the text to a value that is Invalid. The line edit will emit the returnPressed and editingFinished signals only when the validator validates input as Acceptable.

Here's an example where we use a QIntValidator and a QRegularExpressionValidator

python from PyQt6.QtCore import QRegularExpression from PyQt6.QtGui import QIntValidator, QRegularExpressionValidator from PyQt6.QtWidgets import ( QApplication, QFormLayout, QLabel, QLineEdit, QWidget, ) class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Input Validators") self.resize(300, 100) self.int_line_edit = QLineEdit(parent=self) self.int_line_edit.setValidator(QIntValidator()) self.uppercase_line_edit = QLineEdit(parent=self) input_validator = QRegularExpressionValidator( QRegularExpression("[A-Z]+"), self.uppercase_line_edit ) self.uppercase_line_edit.setValidator(input_validator) self.uppercase_line_edit.returnPressed.connect(self.update_label) self.signal_label = QLabel(parent=self) layout = QFormLayout() layout.addRow("Integers:", self.int_line_edit) layout.addRow("Uppercase letters:", self.uppercase_line_edit) layout.addRow("Signal:", self.signal_label) self.setLayout(layout) def update_label(self): self.signal_label.setText("Return pressed!") if __name__ == "__main__": app = QApplication([]) window = Window() window.show() app.exec()

In this example, we have two line edits. In the first line edit, we've used a QIntValidator object. This way, the line edit will only accept valid integer numbers. If you try to type in something different, then the line edit won't accept your input.

In the second line edit, we've used a QRegularExpressionValidator. In this specific case, the regular expression accepts one or more uppercase letters. Again if you try to enter something else, then the line edit won't accept the input.

The QLabel will show the text Return pressed! if the input in the second line edit is valid and you press the Enter key. Here's what the app looks like:

QLineEdit with input validator.

Validators provide a quick way to restrict the user input and set our own validation rules. This way, we can ensure valid user input in our applications.

Conclusion

Line edits are pretty useful widgets in any GUI application. They allow text input through a single-line editor that has many cool features.

In this tutorial, you've learned how to create, use, and customize your line edits while building a GUI application with PyQt/PySide.

Categories: FLOSS Project Planets

Kay Hayen: Nuitka Release 2.0

Sun, 2024-02-04 18:00

This is to inform you about the new stable release of Nuitka. It is the extremely compatible Python compiler, “download now”.

This release had focus on new features and new optimization. There is a really large amount of compatibility with things newly added, but also massive amounts of new features, and esp. for macOS and Windows, lot of platform specified new abilities and corrections.

Bug Fixes
  • Fix, workaround for private functions as Qt slots not having names mangled. Fixed in 1.9.1 already.

  • Fix, when using Nuitka with pdm it was not detected as using pip packages. Fixed in 1.9.1 already.

  • Fix, for pydantic our lazy loader parser didn’t handle all cases properly yet. Fixed in 1.9.1 already.

  • Standalone: Added data files for pyocd package. Fixed in 1.9.1 already.

  • Standalone: Added DLL for cmsis_pack_manager package. Fixed in 1.9.1 already.

  • Standalone: Fix, the specs expanded at run time in some causes could contain random characters. Fixed in 1.9.2 already.

  • Fix, {"a":b, ...}.get("b") could crash at runtime. Fixed in 1.9.2 already.

  • Standalone: Added data files for pyproj package. Fixed in 1.9.2 already.

  • Standalone: Added more metadata requirements for transformers package. Fixed in 1.9.2 already.

  • Plugins: Fix, could crash when including packages from the command line, if they had yaml configuration that requires checking the using module, e.g. anti-bloat work. Fixed in 1.9.3 already.

  • Standalone: Added support for delphifmx package. Fixed in 1.9.4 already.

  • Android: Fix, cannot exclude libz on that platform, it’s not a full Linux OS. Fixed in 1.9.3 already.

  • Standalone: Add needed DLLs for bitsandbytes package. Fixed in 1.9.3 already.

  • Windows: Fix, newer joblib was not working anymore. Fixed in 1.9.3 already.

  • Windows: Fix, could crash when working with junctions that switch drives. Fixed in 1.9.3 already.

  • Fix, was crashing with poetry installed environments. Fixed in 1.9.3 already.

  • Standalone: Added support for newer chromadb package. Fixed in 1.9.3 already.

  • Fix, could crash in report creation on modules excluded that were asked via command line for inclusion. Fixed in 1.9.3 already.

  • Anti-Bloat: Fix for newer streamlit, it was causing SyntaxError for the compilation. Fixed in 1.9.4 already.

  • Arch: Added support for their OS release file location too. Fixed in 1.9.4 already.

  • Windows: Fix, MinGW64 doesn’t accept chinese module names a C source files. Use short paths for these instead. Fixed in 1.9.4 already.

  • Standalone: Added missing DLL for libusb_package package. Fixed in 1.9.4 already.

  • Fix, properly skip directories with non-module top level names when trying to find top level packages of distributions. Fixed in 1.9.4 already.

  • Fix, avoid memory leak bug in triggered by rich package. Fixed in 1.9.4 already.

  • Python3.11+: Fix, didn’t detect non-keywords on star dict calls in some cases. Fixed in 1.9.4 already.

  • Fix, avoid crashes due to unrecognized installers on macOS and Windows, some packages that are built via legacy fallbacks of certain pip versions do not leave any indication of their origin at all. Fixed in 1.9.4 already.

  • Windows: Fix, need to indicate that the program is long path aware or else it cannot work with the paths. Fixed in 1.9.4 already.

  • Debian: The extern namespace might not exist in the pkg_resources module, make the code work with versions that remove it and use the proper external package names then. Fixed in 1.9.6 already.

  • Compatibility: Fix, need to also have .exists method in our files reader objects. Fixed in 1.9.5 already.

  • macOS: Fix, PyQt5 standalone can fail due to libqpdf too.

  • Compatibility: Make dill-compat plugin support module mode too, previously this only worked for executables only. Fixed in 1.9.6 already.

  • Standalone: Added data file for curl_cffi package. Fixed in 1.9.6 already.

  • Windows: Fix warnings given by MinGW64 in debug mode for onefile compilation. Fixed in 1.9.6 already.

  • Python2: The handling of DLL permission changes was not robust against using unicode filenames. Fixed in 1.9.7 already.

  • Python2: Fix, could crash on Debian packages when detecting their installer. Fixed in 1.9.7 already.

  • Standalone: Added required data file for astor package. Fixed in 1.9.7 already.

  • Reports: Fix, in case of build crashes during optimization, the bug report creation could be crashing because the module is not in the list of done modules yet. Fixed in 1.9.7 already.

  • Python2: Fix, unittest.mock was not yet available, code attempting to use it was crashing the compilation. Fixed in 1.9.7 already.

  • Accelerated: Fix, tensorflow configuration removing site usage needs to apply only to standalone mode. Fixed in 1.9.7 already.

  • Plugins: Fix, the get_dist_name Nuitka package configuration function could crash in some rare configurations. Fixed in 1.9.7 already.

  • Standalone: Added necessary data file for pygame package. Added in 1.9.7 already.

  • Standalone: Fix, was not properly handling standard library overloading module names for decisions. Inclusion and compilation mode were made as if the module was part of the standard library, rather than user code. This is now properly checking if it’s also an actual standard library module.

  • Plugins: Fix, crashing on missing absence message with no UPX binary was found.

  • Windows: Fix, couldn’t load extension modules from UNC paths, so standalone distributions failed to launch from network drives. This now works again and was a regression from adding support for symlinks on Windows.

  • Standalone: Added support for non-legacy pillow in imageio package.

  • Standalone: Added required easyOCR data file.

  • Nuitka-Python: Fix, do not demote to non-LTO for “too many” modules there in the default auto mode, it doesn’t work without it.

  • Fix, python setup.py install could fail. Apparently it tries to lookup Nuitka during installation, which then could fail, due to hacks we due to make sure wheels are platform dependent. That hack is of course not really needed for install, since no collision is going to happen there.

  • macOS: Fix, the standard matplotlib plugin that uses native UI was not included yet, and it was also not working due to bindings requiring uncompiled functions, which is now worked around.

  • Compatibility: Add back PySide6 workaround for overloading names like update with slots.

  • Standalone: Added geopandas data files.

  • Python2: Fix, code objects must be made from str exactly, unicode however was used in some configurations after recent improvements to the run time path handling.

  • Standalone: Added missing data files for boto, the predecessor of boto3 as well.

  • Standalone: Added missing DLL for tensorflow factorization module.

  • Compatibility: Fix, PySide2 and PySide6 signal disconnection without arguments were not working yet.

  • Standalone: Added support for toga.

  • Scons: Fix, need to Avoid picking up clang from PATH on Windows with --clang provided, as only our winlibs version is really working.

  • Fix, version of setuptools when included (which we try to avoid very much) was None which breaks some users of it, now it’s the correct version so checks of e.g. setuptools_scm can succeed.

  • Fix, icon options for platforms were conflated, so what should be windows only icon could get used on other platforms as well.

  • Fix, could not create compiled methods from compiled methods. Also now errors out for invalid types given properly.

New Features
  • Plugins: Added support for module decisions, these are parameters provided by the user which can be used to influence the Nuitka per package configuration with a new get_parameter function. We are using these to control important choices in the user, sometimes warning it to make that decision, if the default can be considered problematic.

  • Plugins: Added support for variables in Nuitka package configurations. We can now query at compile time, values from installed packages and use them, e.g. to know what backend is to be used.

  • Standalone: Added module decision to disable Torch JIT. This is generally the right idea, but the decision is still asked for since some packages and programs want to do Torch Tracing, and that is then disabled as well. This makes a bunch of transformers programs work.

  • Standalone: Added module decision to disable Numba JIT. This makes numba work in some cases, but not all. Some packages go very deep with JIT integration, but simpler uses will now compile.

  • New option --include-onefile-external-data allows you to specify file patterns that you included by other data files others, but to put those files not inside, but on the outside of the onefile binary. This makes it easier to create deployments fully within Nuitka project configuration, and to change your mind back and forth without adding/removing the data file option.

  • macOS: Added new value auto for detecting signing identity, if only one is available in the system.

  • macOS: Added support for --copyright and --trademark information to be in app bundles as well, this was previously Windows only.

  • Windows: Added support for using junctions in the Python environment, these are used e.g. when installing via scoop. Added in 1.9.2 already.

  • Added option --cf-protection to select the control flow protection mode for the GCC compiler and deviate from default values of some environments to less strict values.

  • Reports: Added output filename to report, mainly intended for automatically locating the compilation result independent of options used.

  • Plugins: Now provides a checksum for yaml files, but not yet verifies them at runtime, to ask the user to run the checker tool to update it when they make modifications.

  • Windows: Detect when we create too large compiled executables. There is a limit of 2GB that you might e.g. violate by attempting to embed very large files. This doesn’t cover onefile yet.

  • Watch: The tool can now create PRs with the changes in Nuitka-Watch for merging, this is for using it in the CI.

  • Watch: Scanning for Python versions now requires pipenv to be installed in them to be found.

  • Watch: Added ability to create branch and PR from watch run results.

  • Plugins: Added overridden-environment-variables feature to package configuration. These are environment variable changes that only last during the import of that module and are undone later.

  • Plugins: Added force-environment-variables feature to package configuration. These are environment variable changes done on module import that are not undone.

  • Nuitka-Action: Nuitka options that can be given multiple times, cannot be specified multiple times in your workflow. As a workaround, Nuitka now allows in Actions, to use new lines as separator. This is best done with this kind of quoting a multiline string.

    include-data-dir: | a=b c=d
  • The Nuitka package configuration no-auto-follow now applies recursively, i.e. that a top level package can have it, and not every sub-package that uses a package but should not be automatically followed, does have to say this. With this e.g. networkx configuration became simpler, and yet covered automatically older versions as well, and future changes too.

  • Windows: Added support for compiling in case sensitive folders. When this option is enabled, using os.path.normcase can make filenames not found, so with a few cleanups, for lazy code that wasn’t really using the APIs designed for comparisons and filename suffix testing, this works now better.

  • The __compiled__ value has a new attribute containing_dir that allows to find where a module, accelerate executable, a standalone dist folder, a macOS app bundle, or the onefile binary lives in a consistent fashion. This allows esp. better use than sys.argv[0] which points deep into the .app bundle, and can be used cross platform.

Optimization
  • Scalability: Avoid variables that are not shared to be treated as if they were, marking their type shape as tshape_unknown in the first micro pass. These micro passes are not visible, but basically constitute a full visit of the module tree over and over, until no more optimization is changing it. This can lead to quicker resolution, as that unknown type shape effectively disallowed all optimization for variables and reduce the number of necessary micro passes by one.

  • Escaped variables did provide a type shape tshape_unknown and while a lot of optimization looks for value knowledge, and gets by the escaped nature of the value, sometimes, this was seriously inhibiting some of the type based optimization.

  • Loop type shape analysis now succeeds in detecting the types for this code example, which is sort of a break-through for future performance enhancements in generated code.

    # Initial the value of "i" is "NUITKA_NINT_UNASSIGNED" in its # indicator part. The C compiler will remove that assignment # as it's only checked in the assignment coming up. i = 0 # Assignment from a constant, produces a value where both the C # and the object value are value. This is indicated by a value # of "NUITKA_NINT_BOTH_VALID". The code generation will assign # both the object member from a prepared value, and the clong # member to 0. # For the conditional check, "NUITKA_NINT_CLONG_VALID" will # always be set, and therefore function will resort to comparing # that clong member against 9 simply, that will always be very # fast. Depending on how well the C compiler can tell if an overflow # can even occur, such that an object might get created, it can even # optimize that statically. In this case it probably could, but we # do not rely on that to be fast. while i < 9: # RICH_COMPARE_LT_CBOOL_NINT_CLONG # Here, we might change the type of the object. In Python2, # this can change from ``int`` to ``long``, and our type # analysis tells us that. We can consider another thing, # not "NINT", but "NINTLONG" or so, to special case that # code. We ignore Python2 here, but multiple possible types # will be an issue, e.g. list or tuple, float or complex. # So this calls a function, that returns a value of type # "NINT" (actually it will become an in-place operation # but lets ignore that too). # That function is "BINARY_OPERATION_ADD_NINT_NINT_CLONG"(i, 1) # and it is going to check if the CLONG is valid, add the one, # and set to result to a new int. It will reset the # "NUITKA_NINT_OBJECT_VALID" flag, since the object will not be # bothered to create. i = i + 1 # Since "NUITKA_INT_OBJECT_VALID" not given, need to create the # PyObject and return it. return i
  • Python3.11+: Use tomllib from standard library for our distutils integration into pyproject based builds.

  • Avoid late specialization for None returns in generators and do it during tree building already, to remove noise.

  • Added successful detection of static libpython for self compiled Python Linux and macOS. This makes it work with pyenv as well.

  • Standalone: Avoid including .pyx files when scanning for data files, these are code files too, in this case source files that are definitely unused most of the time.

  • macOS: Make static libpython default with CPython for more compact standalone distribution and faster binaries.

  • Remove non-existent entries from sys.path, avoiding many file system lookups during import scans.

  • Anti-Bloat: Avoid using triton in torch package in more cases. Added in 1.9.2 already.

  • Anti-Bloat: Avoid using pytest in knetworkx package in more cases. Added in 1.9.2 already.

  • Anti-Bloat: Avoid using IPython in distributed package. Added in 1.9.3 already.

  • Anti-Bloat: Avoid using dask in skimage. Added in 1.9.3 already.

  • Anti-Bloat: Avoid using triton in the bitsandbytes package. Added in 1.9.3 already.

  • Anti-Bloat: Avoid IPython in tf_keras package as well. Added in 1.9.6 already.

  • Anti-Bloat: Avoid unittest in mock.mock module. Added in 1.9.7 already.

  • Avoid importing setuptools_scm during compilation when using the tqdm inline copy, this also avoids a warning on Ubuntu. Added in 1.9.7 already.

  • Anti-Bloat: Avoid doctest in skimage in their tifffile inline copy as well. Added in 1.9.7 already.

  • Anti-Bloat: Avoid h5py.tests with older h5py as well. Added in 1.9.7 already.

  • Anti-Bloat: Using distributed.utils_test is also considered using pytest.

  • Anti-Bloat: Avoid IPython in the pip package.

  • Anti-Bloat: Avoid site module for older tensorflow versions too.

  • Anti-Bloat: Avoid more unittest usages in tensorflow packages.

  • Anti-Bloat: Avoid nose in skimage package.

  • Anti-Bloat: Avoid nose in networkx package.

  • Anti-Bloat: Avoid nose in pywt package.

Organisational
  • UI: Change template paths over from %VAR% to {VAR}.

    The old spec values are migrated transparently and continue to work, but get a warning when used.

    The new code detects unknown variable names and more formatting issues than before.

    Using only the {PID} value for process ID, is now making it temporary value for onefile, that was previously a bug.

    The main benefit and reason of doing this, is that Windows CMD.EXE does expand those values before Nuitka sees them as even with quoting %TEMP% is the current one on the building machine, a recipe for disaster. As some people still use that, and e.g. os.system or subprocess with shell=True will use it too, this is just not sustainable for a good user experience.

    As a result, compile time and run time variables now clash, there is e.g. {VERSION} (program version information given) and {Version} (Nuitka version), and we should clean that up too.

  • Project: Added Code of Conduct. Adapted from the one used in the Linux kernel.

  • UI: Warnings given by Nuitka used to be in red color, changed those to be yellow for consistency.

  • User Manual: Added pointer for Nuitka-Action Nuitka-Action for users interested in using Nuitka in GitHub workflows.

  • Added .gitignore to build folder that just causes these folders to be ignored by git.

  • User Manual: Added information on how to debug fork bombs from created binaries.

  • Debugging: The output of --experimental=--report-refcounts that we use to show leaks of compiled time objects at program exit, now counts and reports on functions, generator objects and compiled cells as well.

  • Quality: Warnings from yamllint not disabled are errors. These were only output, but didn’t cause the autoformat to error exit yet.

  • UI: Enhanced formatting of info traces, drop the :INFO part that shouts, and reserve that for errors and warnings. Also format info messages to make sure they fit into the line.

  • UI: Changed --show-source-changes to accept module pattern to make it easier to only see the ones currently being worked on. To get the old behavior of showing everything, use * as a pattern.

  • UI: Allow using ~ in data files source path for command line options and expand it properly.

  • Quality: Enhanced schema for our package configuration yaml files to detect suffixes with leading dots, that is not wanted. These now fail checks, but we also tolerate them now.

  • Quality: Check module names used in the package configuration yaml files for validity, this catches e.g. trailing dots.

  • Quality: Make sure to really prefer clang-format from Visual Code and MSVC for formatting C code, otherwise a system installed one could be used that gives slightly different outputs.

  • Scons: Allow disabling to enforce no warnings for C compilation

    Currently only for gcc, where we need it until loop tracing is better, we can now use --experimental=allow-c-warnings options to make --debug work for some known currently unavoidable warnings.

  • macOS: Make --macos-create-app-bundle imply standalone mode, it’s not working or useful for accelerated mode anyway.

  • Standalone: Added support for using self-compiled Python versions that are not installed on Linux and macOS. This avoids having to do make install and can ease debugging with changes made in Python core itself. Added in 1.9.6 already.

  • Release: Added ability to simple re-date hotfixes. Previously the version bump commit needed to be dropped, now a fixup commit is easy to generate.

  • Release: Man pages are no longer built during package builds, but are available statically in the git, which should make it easier.

  • Release: Disable verbose output in package installation of Nuitka, it never was any use, and just makes things hard to read.

  • UI: Check user yaml file present immediately. Otherwise it was crashing when parsing yaml files first time with less comprehensible exceptions. Added in 1.9.7 already.

  • Quality: Updated to latest rstfmt, black and isort versions.

  • Debian: Remove references to PDF documentation that no longer exists.

  • Quality: Do not crash when collecting modified files due to deleted files.

  • UI: Detect the Alpine flavor of Python as well.

  • UI: Detect manylinux Pythons as a Python flavors as well.

  • UI: Detect self compiled uninstalled Python as a dedicated flavor.

Cleanups
  • For the Nuitka-Action part of the available options is now generated from Nuitka option definitions itself, adding some previously missing options as a result. As a result, adding --include-onefile-external-data was automatic this time.

  • The warnings for onefile only options without onefile mode provided have been moved to common code, and in some cases were having wrong texts corrected.

  • Use enum definitions in the Nuitka package configuration schema rather than manual oneOf types.

  • The User Manual was proof read and had a bunch of wordings improved.

  • Cleanup, avoid “unused but set variable” warning from the C compiler for hard some forms of hard imports.

  • Prefer os.getenv over os.environ.get for readability.

  • Changed parts of the C codes that clang-format had a hard time with to something more normal.

Tests
  • When locating the standalone binary created, use a compilation report and resolve the path specified there. This allows macOS app bundles to be used in these tests as well.

  • Made the PyQt tests executable on macOS too adding necessary options.

  • Added reference test case for unpacking into a list, this was not covered but under suspect of reference leaking which turns out to be wrong.

  • Much enhanced usage of virtualenv in the distutils test cases. We make more sure to delete them even in case of issues. We disable warnings during Nuitka package installation. The code to execute a case was factored out and became more clear. We now handle errors in execution with stating what case actually failed, this was a bit hard to tell previously. Also do not install Nuitka when a pyproject case is used, since the build tool installs Nuitka itself.

Summary

This release deserves the 2.0 marker, as it is ground breaking in many ways. The loop type analysis stands out on the optimization front. This will open an avenue for much optimized code at least for some benchmark examples this summer.

The new features for package configuration, demonstrate abilities to avoid plugins for Nuitka, where those previously would have been used. The new variables and parameters made it unnecessary to have them, and still add compile time variable use and user decisions and information, without them.

The scope of supported Python configurations got expanded a bit, and the the usual slew of anti-bloat work and new packages supported, makes Nuitka an ever more round package.

The improved user dialog with less noisy messages and slightly better coloring, continues a trend, where Nuitka becomes more and more easy to use.

Categories: FLOSS Project Planets

TechBeamers Python: How to Find the List Shape in Python

Sun, 2024-02-04 14:25

Welcome to this short tutorial where we’ll explore how to get the list shape in Python. This knowledge becomes essential when working with multi-dimensional data structures, like lists of lists a.k.a. nested lists or NumPy arrays. Let’s dive into the methods available to achieve this in Python with some good examples. What Does a List […]

The post How to Find the List Shape in Python appeared first on TechBeamers.

Categories: FLOSS Project Planets

Pages