Feeds

Real Python: Dictionaries in Python

Planet Python - Mon, 2024-12-16 09:00

Python dictionaries are a powerful built-in data type that allows you to store key-value pairs for efficient data retrieval and manipulation. Learning about them is essential for developers who want to process data efficiently. In this tutorial, you’ll explore how to create dictionaries using literals and the dict() constructor, as well as how to use Python’s operators and built-in functions to manipulate them.

By learning about Python dictionaries, you’ll be able to access values through key lookups and modify dictionary content using various methods. This knowledge will help you in data processing, configuration management, and dealing with JSON and CSV data.

By the end of this tutorial, you’ll understand that:

  • A dictionary in Python is a mutable collection of key-value pairs that allows for efficient data retrieval using unique keys.
  • Both dict() and {} can create dictionaries in Python. Use {} for concise syntax and dict() for dynamic creation from iterable objects.
  • dict() is a class used to create dictionaries. However, it’s commonly called a built-in function in Python.
  • .__dict__ is a special attribute in Python that holds an object’s writable attributes in a dictionary.
  • Python dict is implemented as a hashmap, which allows for fast key lookups.

To get the most out of this tutorial, you should be familiar with basic Python syntax and concepts such as variables, loops, and built-in functions. Some experience with basic Python data types will also be helpful.

Get Your Code: Click here to download the free sample code that you’ll use to learn about dictionaries in Python.

Take the Quiz: Test your knowledge with our interactive “Python Dictionaries” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Python Dictionaries

Test your understanding of Python dictionaries

Getting Started With Python Dictionaries

Dictionaries are one of Python’s most important and useful built-in data types. They provide a mutable collection of key-value pairs that lets you efficiently access and mutate values through their corresponding keys:

Python >>> config = { ... "color": "green", ... "width": 42, ... "height": 100, ... "font": "Courier", ... } >>> # Access a value through its key >>> config["color"] 'green' >>> # Update a value >>> config["font"] = "Helvetica" >>> config { 'color': 'green', 'width': 42, 'height': 100, 'font': 'Helvetica' } Copied!

A Python dictionary consists of a collection of key-value pairs, where each key corresponds to its associated value. In this example, "color" is a key, and "green" is the associated value.

Dictionaries are a fundamental part of Python. You’ll find them behind core concepts like scopes and namespaces as seen with the built-in functions globals() and locals():

Python >>> globals() { '__name__': '__main__', '__doc__': None, '__package__': None, ... } Copied!

The globals() function returns a dictionary containing key-value pairs that map names to objects that live in your current global scope.

Python also uses dictionaries to support the internal implementation of classes. Consider the following demo class:

Python >>> class Number: ... def __init__(self, value): ... self.value = value ... >>> Number(42).__dict__ {'value': 42} Copied!

The .__dict__ special attribute is a dictionary that maps attribute names to their corresponding values in Python classes and objects. This implementation makes attribute and method lookup fast and efficient in object-oriented code.

You can use dictionaries to approach many programming tasks in your Python code. They come in handy when processing CSV and JSON files, working with databases, loading configuration files, and more.

Python’s dictionaries have the following characteristics:

  • Mutable: The dictionary values can be updated in place.
  • Dynamic: Dictionaries can grow and shrink as needed.
  • Efficient: They’re implemented as hash tables, which allows for fast key lookup.
  • Ordered: Starting with Python 3.7, dictionaries keep their items in the same order they were inserted.

The keys of a dictionary have a couple of restrictions. They need to be:

  • Hashable: This means that you can’t use unhashable objects like lists as dictionary keys.
  • Unique: This means that your dictionaries won’t have duplicate keys.

In contrast, the values in a dictionary aren’t restricted. They can be of any Python type, including other dictionaries, which makes it possible to have nested dictionaries.

It’s important to note that dictionaries are collections of pairs. So, you can’t insert a key without its corresponding value or vice versa. Since they come as a pair, you always have to insert a key with its corresponding value.

Note: In some situations, you may want to add keys to a dictionary without deciding what the associated value should be. In those cases, you can use the .setdefault() method to create keys with a default or placeholder value.

Read the full article at https://realpython.com/python-dicts/ »

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

Categories: FLOSS Project Planets

PyCharm: 7 Reasons You Should Use dbt Core in PyCharm

Planet Python - Mon, 2024-12-16 07:58

dbt Core is a modern data transformation framework. It doesn’t extract or load data and is only responsible for the T in the ELT (extract-load-transform) process. dbt connects to your data warehouse and helps you prepare your data so it can later be used to answer business questions.

In this blog post, we’ll talk about the top benefits of dbt and the advantages of using it in PyCharm Professional. To make the most of these features, you should be familiar with the framework. If you know SQL well, you’ll likely find it easy to use, and if you are a total novice in the field, you can use the dbt portal to get acquainted with it.

Why you should use dbt
  • Modularity and code reusability – Transformations can be saved into modular, reusable models. For instance, in this example the model int_count_customer.sql has a reference to stg_day_customer.sql and reuses its code.
  • Versioning – dbt projects can be stored in version control systems like Git or GitHub. This allows you to track changes, collaborate with other team members, and maintain a record of all transformations.
  • Testing – dbt allows you to write tests for your data models easily and check whether the data has any duplicates or null values. Additionally, you can even create specific rules to test against, and you can perform tests on both the model and the project levels.
  • Documentation – dbt auto-generates documentation for data models, ensuring that team members and stakeholders all understand the data lineage and model definitions in the same way.

To summarize, dbt brings best practices in engineering to the field of data analysis, allowing you to produce higher-quality results while providing you with a straightforward and intuitive workflow.

These benefits are just the tip of the iceberg when it comes to what the tool can do.

How PyCharm streamlines your dbt workflow

Having established the benefits of dbt, we can now turn to the 7 key reasons to use it in PyCharm:

1. User-friendly onboarding – PyCharm streamlines the initial setup. As demonstrated in this video, setting up a project and configuring the necessary settings is straightforward. 

2. Unified workspace for databases and dbt – PyCharm’s integrated database plugin powered by JetBrains DataGrip makes handling SQL databases significantly easier. Since it’s compatible with all databases that dbt works with, you don’t have to worry about juggling multiple tools. You can focus on data modeling and instantly view outcomes all in one place. To cover even a small number of the plugin’s features would take hours, but luckily we have a nice set of webinars dedicated to PyCharm’s functionality for databases:  Visual SQL Development with PyCharm.

3. Git and dbt integration – In one interface, you can easily clone the repo, track any changes, manage branches, resolve conflicts, and collaborate with teammates.

4. Autocompletion for your .yml  and jinja-template SQL files – People love using PyCharm because of its smart autocompletion, which it, of course, offers for dbt as well.

5. Local history –This feature lets you undo recent changes if they cause problems. You can also compare different versions to see what was changed and check whether updates were made correctly.

6. AI Assistant – AI Assistant is really helpful, especially if you’re just starting with dbt Core. It is context-aware, and in addition to having it answer your questions in the AI chat, you can have it generate code and fix problems for you, streamlining your work with data models. It also saves you from worrying about what to write in commit messages by composing them for you.

7. Project navigation – PyCharm excels in project navigation, offering features like fast search functionality and the Go to Declaration feature, both of which allow you to navigate through your dbt models effortlessly.

That’s just a glimpse of the benefits PyCharm already offers for dbt, and our support is still in its early stages. We invite you to test it out and share your insights. Whether you have suggestions for features or want to let us know about areas for improvement, we’re eager to hear from you. 

Get started with PyCharm by using the promo code dbt-PyCharm to get a 3-month free trial.

Redeem your code

Want to learn how to use dbt in PyCharm? Head to the documentation page to learn more about the IDE’s dbt support.

Eager to learn more about dbt in general? Take a look at this post on the experience of using dbt and this analysis of deeper dbt concepts by Pavel Finkelshteyn.

Categories: FLOSS Project Planets

The Drop Times: QED42 Debuts AI-Powered Twig-to-SDC Module

Planet Drupal - Mon, 2024-12-16 07:35
Revolutionize your Drupal development with QED42's new Twig to Single-Directory Components (SDC) Generator! Powered by Generative AI, this cutting-edge module automates the conversion of Twig components, saving time and effort for developers. Don't miss this game-changing tool that's redefining Drupal workflows — check it out now!
Categories: FLOSS Project Planets

CKEditor: CKEditor 5 introduces self-service licensing and version override for Drupal

Planet Drupal - Mon, 2024-12-16 07:04
The CKEditor 5 Premium Features module for Drupal now supports self-service licensing plans introduced in version 44.0.0, enabling users to integrate premium features seamlessly. Additionally, the new Version Override Submodule allows manual upgrades of CKEditor 5 within Drupal projects, ensuring access to the latest editor capabilities regardless of the Drupal core version. Notably, CKEditor 5 was incorporated into Drupal Core in version 9.5 and became the default rich text editor in version 10.0. These enhancements provide Drupal users with greater flexibility and control over their content editing environments.
Categories: FLOSS Project Planets

Qt Creator 15 - CMake Update

Planet KDE - Mon, 2024-12-16 05:49

Here are the new CMake features and fixes in Qt Creator 15:

Categories: FLOSS Project Planets

Python Bytes: #414 Because we are not monsters

Planet Python - Mon, 2024-12-16 03:00
<strong>Topics covered in this episode:</strong><br> <ul> <li><strong><a href="https://micro.webology.dev/2024/12/14/new-project-to.html?featured_on=pythonbytes">New project to shorten django-admin to django because we are not monsters</a></strong></li> <li><strong><a href="https://github.com/adamghill/django-unicorn?featured_on=pythonbytes">django-unicorn</a>: The magical reactive component framework for Django <img src="https://paper.dropboxstatic.com/static/img/ace/emoji/2728.png?version=8.0.0" alt="sparkles" /></strong></li> <li><strong><a href="https://nedbatchelder.com/blog/202412/testing_some_tidbits.html?featured_on=pythonbytes">Testing some tidbits</a></strong></li> <li><strong><a href="https://blog.jetbrains.com/pycharm/2024/12/the-state-of-python/?featured_on=pythonbytes">The State of Python 2024 article</a></strong></li> <li><strong>Extras</strong></li> <li><strong>Joke</strong></li> </ul><a href='https://www.youtube.com/watch?v=y1_HzSE83jc' style='font-weight: bold;'data-umami-event="Livestream-Past" data-umami-event-episode="414">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/?featured_on=pythonbytes"><strong>courses at Talk Python Training</strong></a></li> <li><a href="https://courses.pythontest.com/p/the-complete-pytest-course?featured_on=pythonbytes"><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> <strong>/</strong> <a href="https://bsky.app/profile/mkennedy.codes?featured_on=pythonbytes"><strong>@mkennedy.codes</strong></a> <strong>(bsky)</strong></li> <li>Brian: <a href="https://fosstodon.org/@brianokken"><strong>@brianokken@fosstodon.org</strong></a> <strong>/</strong> <a href="https://bsky.app/profile/brianokken.bsky.social?featured_on=pythonbytes"><strong>@brianokken.bsky.social</strong></a></li> <li>Show: <a href="https://fosstodon.org/@pythonbytes"><strong>@pythonbytes@fosstodon.org</strong></a> <strong>/</strong> <a href="https://bsky.app/profile/pythonbytes.fm"><strong>@pythonbytes.fm</strong></a> <strong>(bsky)</strong></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 <strong>Monday</strong> at 10am PT. Older video versions available there too.</p> <p>Finally, if you want an artisanal, hand-crafted digest of every week of the show notes in email form? Add your name and email to <a href="https://pythonbytes.fm/friends-of-the-show">our friends of the show list</a>, we'll never share it. </p> <p><strong>Brian #1:</strong> <a href="https://micro.webology.dev/2024/12/14/new-project-to.html?featured_on=pythonbytes">New project to shorten django-admin to django because we are not monsters</a></p> <ul> <li>Jeff Tripplet has created <a href="https://github.com/jefftriplett/django-cli-no-admin?featured_on=pythonbytes">django-cli-no-admin</a> to shorten django-admin to just django.</li> <li>“One of the biggest mysteries in Django is why I have to run django-admin from my terminal instead of just running django. Confusingly, django-admin has nothing to do with Django’s admin app.”</li> <li>Instead of typing things like: django-admin startproject mysite projectname</li> <li>We can type the shorter: django startproject mysite projectname</li> <li>I love this kind of developer speedup / comfort improvements</li> <li>And yes, Jeff wants Django to eventually include this as the default way to run the command line utilities.</li> </ul> <p><strong>Michael #2:</strong> <a href="https://github.com/adamghill/django-unicorn?featured_on=pythonbytes">django-unicorn</a>: The magical reactive component framework for Django <img src="https://paper.dropboxstatic.com/static/img/ace/emoji/2728.png?version=8.0.0" alt="sparkles" /></p> <ul> <li>Add modern site functionality: Quickly add in simple interactions to regular Django templates without learning a new templating language.</li> <li>Skip the JavaScript build tools</li> <li>No API required: Skip creating a bunch of serializers and just use Django.</li> </ul> <p><strong>Brian #3:</strong> <a href="https://nedbatchelder.com/blog/202412/testing_some_tidbits.html?featured_on=pythonbytes">Testing some tidbits</a></p> <ul> <li>Ned Batchelder</li> <li>Different ways to test to see if a string has only 0 or 1 in it.</li> <li>And also, a way to check all the different ways to make sure they work.</li> <li>Fun post, and I learned about <ul> <li>cleandoc - a way to strip leading blank space and maintain code block indentation <ul> <li>I usually use textwrap.dedent()</li> </ul></li> <li>partition - splitting strings based on a substring</li> <li>Using | to pass imports to eval() - I don't use eval much.</li> </ul></li> <li>However, no pytest! </li> <li>Here’s a way to check all this with pytest: <ul> <li><a href="https://pythontest.com/pytest/testing-tidbits-pytest/?featured_on=pythonbytes">Testing some tidbits with pytest</a></li> </ul></li> </ul> <p><strong>Michael #4:</strong> <a href="https://blog.jetbrains.com/pycharm/2024/12/the-state-of-python/?featured_on=pythonbytes">The State of Python 2024 article</a></p> <ol> <li>Python usage with other languages drops as general adoption grows</li> <li>41% of Python developers have under 2 years of experience</li> <li>Python learning expands through diverse channels</li> <li>The Python 2 vs. 3 divide is in the distant past</li> <li>Flask, Django, and FastAPI remain top Python web frameworks</li> <li>Most Python web apps run on hyperscale clouds</li> <li>Containers over VMs over hardware</li> <li>uv takes Python packaging by storm</li> </ol> <p><strong>Extras</strong> </p> <p>Brian:</p> <ul> <li>More Django: <a href="https://draculatheme.com/django-admin?featured_on=pythonbytes">Dracula Theme for Django Admin</a></li> </ul> <p>Michael:</p> <ul> <li><a href="https://zen-browser.app/?featured_on=pythonbytes">Zen Browser update</a></li> <li><a href="https://bsky.app/profile/did:plc:u4qsxlhzx76gwoyj4xvtxbuf/post/3lcye7a5flk2d?featured_on=pythonbytes">Office refresh</a></li> <li><a href="https://blobs.pythonbytes.fm/transcripts-in-player.webp">Transcripts</a> (in some players)</li> </ul> <p><img src="https://blobs.pythonbytes.fm/transcripts-in-player.webp" alt="" /></p> <p><strong>Joke:</strong></p> <ul> <li><a href="https://bsky.app/profile/mbetm.bsky.social/post/3lcl6qoo43c2q?featured_on=pythonbytes">Volkswagen, passing all the tests </a></li> </ul>
Categories: FLOSS Project Planets

Zato Blog: HL7 FHIR Integrations in Python

Planet Python - Mon, 2024-12-16 03:00
HL7 FHIR Integrations in Python 2024-12-16, by Dariusz Suchojad

HL7 FHIR, pronounced "fire", is a data model and message transfer protocol designed to facilitate the exchange of information among systems used in health care settings.

In such environments, a FHIR server will assume the role of a central repository of health records with other systems integrating with it, potentially in a hub-and-spoke fashion, thus letting the FHIR server become a unified and consistent source of data that would otherwise stay confined to a silo of each individual health information system.

While FHIR is the way forward, the current reality of health care systems is that much of the useful and actionable information is distributed and scattered among many individual data sources - paper-based directories, applications or data bases belonging to the same or different enterprises - and that directly hampers the progress towards delivering good health care. Anyone witnessing health providers copy-and-pasting the same information from one application to another, not having access to the already existing data, not to mention people not having an easy way to access their own data about themselves either, can understand what the lack of interoperability looks like externally.

The challenges that integrators face are two-fold. On the one hand, the already existing systems, including software as well as medical appliances, were often not, or are still not being, designed for the contemporary inter-connected world. On the other hand, FHIR in itself is a relatively new technology which means that it is not straightforward to re-use the existing skills and competencies.

Zato is an open-source platform that makes it possible to integrate systems with FHIR using Python. Specifically, its support for FHIR enables quick on-boarding of integrators who may be new to health care interoperability, who are coming to FHIR with previous experience or interest in web development technologies, and who need an easy way to get started with and to navigate the complex landscape of health care integrations.

Connecting to FHIR servers

Outgoing FHIR connections are what allows Python-based services to communicate with FHIR servers. Throughout the rest of the chapter, the following definition will be used. It connects to a live, publicly available FHIR server.

Filling out the form below will suffice, there is no need for any server restarts. This principle, that restarts are not needed, applies all throughout the platform, whenever you change any piece of configuration, it will be automatically propagated as necessary.

  • Name: FHIR.Sample
  • Address: https://simplifier.net/zato
  • Security: No security definition (we will talk about security later)
  • TLS CA Certs: Default bundle

Retrieving data from FHIR servers

In Python code, you obtain client connections to FHIR servers through self.out.hl7.fhir objects, as in the example below which first refers to the server by its name and then looks up all the patients in the server.

The structure of the Patient resource that we expect to receive can be found here.

# -*- coding: utf-8 -*- # Zato from zato.server.service import Service class FHIService1(Service): name = 'demo.fhir.1' def handle(self) -> 'None': # Connection to use conn_name = 'FHIR.Sample' with self.out.hl7.fhir[conn_name].conn.client() as client: # This is how we can refer to patients patients = client.resources('Patient') # Get all active patients, sorted by their birth date result = patients.sort('active', '-birthdate') # Log the result that we received for elem in result: self.logger.info('Received -> %s', elem['name'])

Invoking the service will store in logs the data expected:

INFO - Received -> [{'use': 'official', 'family': 'Chalmers', 'given': ['Peter', 'James']}]

For comparison, this is what the FHIR server displays in its frontend. - the information is the same.

Storing data in FHIR servers

To save information in a FHIR server, create the required resources and call .save to permanently store the data in the server. Resources can be saved either individually (as in the example below) or as a bundle.

# -*- coding: utf-8 -*- # Zato from zato.server.service import Service class CommandsService(Service): name = 'demo.fhir.2' def handle(self) -> 'None': # Connection to use conn_name = 'FHIR.Sample' with self.out.hl7.fhir[conn_name].conn.client() as client: # First, create a new patient patient = client.resource('Patient') # Save the patient in the FHIR server patient.save() # Create a new appointment object appointment = client.resource('Appointment') # Who will attend it participant = { 'actor': patient, 'status':'accepted' } # Fill out the information about the appointment appointment.status = 'booked' appointment.participant = [participant] appointment.start = '2022-11-11T11:11:11.111+00:00' appointment.end = '2022-12-22T22:22:22.222+00:00' # Save the appointment in the FHIR server appointment.save() Learning what FHIR resources to use

The "R" in FHIR stands for "Resources" and the sample code above uses resources such a Patient or Appointment but how does one learn what other resources exist and what they look like? In other words, how does one learn the underlying data model?

First, you need to get familiar with the spec itself which, in addition to textual information, offers visualizations of the data model. For instance, here is the description of the Observation object, including details such as all the attributes an Observation is composed of as well as their multiplicities.

Secondly, do spend time with FHIR servers such as Simplifier. Use Zato services to create test resources, look them up and compare the results with what the spec says. There is no substitute for experimentation when learning a new data model.

FHIR security

Outgoing FHIR connections can be secured in several ways, depending on what a given FHIR requires:

  • With Basic Auth definitions
  • With OAuth definitions
  • With SSL/TLS. If the server is not a public one (e.g. it is in a private network with a private IP address), you may need to upload the server's certificate to Zato first if you plan to use SSL/TLS because, without it, the server's certificate may be rejected.
MLLP, HL7 v2 and v3

While FHIR is what new deployments use, it is worth to add that there are still other HL7 versions frequently seen in integrations:

  • Version 2, using its own MLLP protocol
  • Version 3, using XML

Both of them can be used in Zato services, in both directions. For instance, it is possible to both receive HL7 v2 messages as well as to send them to external applications. It is also possible to send v2 messages using REST in addition to MLLP.


➤ Read more about using Python in API integrations
Start the tutorial which will guide you how to design and build Python API services for interoperability, integrations and automation
➤ Visit the support center for more articles and FAQ
Open-source iPaaS in Python

More blog posts
Categories: FLOSS Project Planets

Handling incorrect warnings and a limited functionality in QML Code Editor in Qt Creator 14.0 and 15.0

Planet KDE - Mon, 2024-12-16 02:25

We've recently discovered that the QML code editor in Qt Creator 14.0 and 15.0 is not working as expected out of the box. The QML Language Server integration is currently broken, and we’d like to address it openly and provide solutions for those affected.

Categories: FLOSS Project Planets

Russ Allbery: Review: Finders

Planet Debian - Sun, 2024-12-15 23:14

Review: Finders, by Melissa Scott

Series: Firstborn, Lastborn #1 Publisher: Candlemark & Gleam Copyright: 2018 ISBN: 1-936460-87-4 Format: Kindle Pages: 409

Finders is a far future science fiction novel with cyberpunk vibes. It is the first of a series, but the second (and, so far, only other) book of the series is a prequel. It stands alone reasonably well (more on that later).

Cassilde Sam is a salvor. That means she specializes in exploring ancient wrecks and ruins left behind by the Ancients and salvaging materials that can be reused. The most important of those are what are called Ancestral elements: BLUE, which can hold programming; GOLD, which which reacts to BLUE instructions; RED, which produces actions or output; and GREEN, the rarest and most valuable, which powers everything else. Cassilde and her partner Dai Winter file claims on newly-discovered or incompletely salvaged Ancestor sites and then extract elemental material and anything else of value in their small salvage ship.

Cassilde is also dying. She has Lightman's, an incurable degenerative disease that can only be treated with ever-increasing quantities of GREEN. It's hard to sleep, hard to get warm, hard to breathe, and eventually she'll run out of money to pay for the GREEN and she'll die.

To push that day off into the future, she and Dai need work. The good news is that the wreckage of a new Ancestor sky palace was discovered in a long orbit and will create enough salvage work for every experienced salvor in the system. The bad news is that they're not qualified to bid on it. They need a scholar with a class-one license to bid on the best sections, and they haven't had a reliable scholar since their former partner and lover Summerland Ashe picked the opposite side in the Troubles and left the Fringe for the Entente, the more densely settled and connected portion of human space.

But, unexpectedly and suspiciously, Ashe may be back and offering to work with them again.

So, first, I love this setting. This is far from the first SF novel that is set in the aftermath of a general collapse of human civilization and revolving around discovering lost mysteries. Most examples of that genre are post-apocalyptic novels limited to Earth or the local solar system, but Kate Elliott's Unconquerable Sun comes immediately to mind. It's also not the first space archaeology series I've read; Kristine Kathyrn Rusch's story series starting with "Diving into the Wreck" also came to mind. But I don't recall the last time I've seen the author sell the setting so effectively.

This is a world with starships and spaceports and clearly advanced technology, but it feels like a post-collapse society that's built on ruins. It's not just that technology runs on half-understood Ancestral elements and states fight over control of debris fields. It's also that the society repurposes Ancestral remnants in ways that both they and the reader know weren't originally intended, and that sometimes are more ingenious or efficient than how the Ancestors probably used them. There's a creative grittiness here that reminds me of good cyberpunk.

It's not just good atmospheric writing, though. Scott makes a world-building decision that is going to sound trivial when I say it, but that has brilliant implications for the rest of the setting. There was not just one collapse; there were two.

The Ancestor civilization, presumed to be the first human civilization, has passed into myth, quite literally when it comes to the stories around its downfall in the aftermath of a war against AIs. After the Ancestors came the Successors, who followed a similar salvage and rebuild approach and got as far as inventing their own warp drive technology that was based on but different than the Ancestor technology. Then they also collapsed, leaving their adapted technology and salvage operations layered over Ancestor sites. Cassilde's civilization is the third human starfaring civilization, and it is very specifically the third, neither the second nor one of dozens.

This has so many small but effective implications that improve this story. A fall happened twice, so it feels like a pattern that makes Cassilde's civilization paranoid, but it happened for two very different reasons, so there is room to argue against it being a pattern. Salvage is harder because of the layering of Ancestor and Successor activity. Successors had their own way of controlling technology that is not accessible to Cassilde and her crew but is also not how the technology was intended to be used, which sends small ripples of interesting complexity through the background. And salvors are competing not only against each other but also against Successor salvage operations for which they have fragmentary records. It's a beautifully effective touch.

Melissa Scott has been publishing science fiction for forty years, and it shows in this book. The protagonists are older characters: established professionals with resource problems but also social connections and an earned reputation, people who are trying to do a job and live their lives, not change the world. The writing is competent, deft, and atmospheric, with the confidence of long practice, but it also has the feel of an earlier era of science fiction. I mentioned the cyberpunk influence, which shows in the grittiness of the descriptions, the marginality of the characters in society, and the background theme of repurposing and reusing technology in unintended ways. This is the sort of book that feels solidly in the center of science fiction, without the genre mixing into either fantasy or romance that has become somewhat more common, and also without the dramatics of space opera (although the reader discovers that the stakes of this novel may be higher than anyone realized).

And yet, so much of this book is about navigating a complicated romantic relationship, and that's where the story structure felt a bit odd. Cassilde, Dai, and Ashe were a polyamorous triad (polyamory also shows up in Scott's excellent Roads of Heaven series), and much of the first third of the book deals with the fracturing of trust with Ashe and their renegotiation of that relationship given his return. This is refreshingly written as the thoughtful interaction of three adults who take issues of trust seriously, but that also means it's much less dramatic than it sounds, and that means this book starts exceptionally slow. Scott is going somewhere, and the slow build became engrossing around the midpoint of the book, but I had to fight to stick with it at the start.

About 80% of the way through this book, I had no idea how Scott was going to wrap things up in the pages remaining and was bracing myself for some sort of series cliffhanger. This is not what happens; the plot is not fully resolved in every detail, but it reaches a conclusion of sorts that does not mandate a sequel. I did think the end was a little bit unsatisfying, though, and I want another book that explores the implications of the ending. I think it would have to be a much different book, and the tonal shift might be stark.

I've had this book on my to-read list for a while and kept putting it off because I wasn't sure I was in the mood for something precarious and gritty. This turned out to be an accurate worry: this is literally a book about salvaging the pieces of something full of wonders inextricably connected to dangers. You have to be in a cyberpunk sort of mood. But I've never read a bad Melissa Scott book, and this is no exception. The simplicity and ALL-CAPSNESS of the Ancestral elements grated a bit, but apart from that, the world-building is exceptional and well worth the trip. Recommended, although be warned that, if you're like me, it may not grab you from the first page.

Followed by Fallen, but that book is a prequel that does not share any protagonists.

Content notes: disability and degenerative illness in a universe where magical cures are possible, so be warned if that specific thematic combination is not what you're looking for.

Rating: 7 out of 10

Categories: FLOSS Project Planets

Krita Monthly Update - Edition 21

Planet KDE - Sun, 2024-12-15 19:00

Welcome to the @Krita-promo team's November 2024 development and community update.

Development Report Community Bug Hunt Ended

The Community Bug Hunt has ended, with dozens of bugs fixed and over a hundred bug more reports closed. Huge thanks to everyone who participated, and if you missed it, the plan is to make this a regular occurrence.

Can't wait for the next bug hunt to be scheduled? Neither will the bug reports! Help in investigating them is appreciated anytime!

Community Report November 2024 Monthly Art Challenge Results

For the "Fluffy" theme, 22 members submitted 26 original artworks. And the winner is… Most "Fluffy" by @steve.improvthis, featuring three different fluffy submissions. Be sure to check out the other two as well!

The December Art Challenge is Open Now

For the December Art Challenge, @steve.improvthis has chosen "Tropical" as the theme, with the optional challenge of using new or unfamiliar brushes. See the full brief for more details, and find yourself a place in the sun!

Featured Artwork Best of Krita-Artists - October/November 2024

Seven images were submitted to the Best of Krita-Artists Nominations thread, which was open from October 15th to November 11th. When the poll closed on November 14th, these five wonderful works made their way onto the Krita-Artists featured artwork banner:

Ocean | Krita by @Gurkirat_Singh

Winter palace by @Sad_Tea

Order by @Valery_Sazonov

Curly, 10-24 by @Celes

Afternoon Magic by @zeki

Ways to Help Krita

Krita is Free and Open Source Software developed by an international team of sponsored developers and volunteer contributors.

Visit Krita's funding page to see how user donations keep development going, and explore a one-time or monthly contribution. Or check out more ways to Get Involved, from testing, coding, translating, and documentation writing, to just sharing your artwork made with Krita.

The Krita-promo team has put out a call for volunteers, come join us and help keep these monthly updates going.

Notable Changes

Notable changes in Krita's development builds from Nov. 12 - Dec. 11, 2024.

Stable branch (5.2.9-prealpha):
  • General: Fix rounding errors in opacity conversion, which prevented layered 50% brushstrokes from adding up to 100%. (bug report) (Change, by Dmitry Kazakov)
  • General: Fix snapping to grid at the edge of the canvas. (bug report) (Change, by Dmitry Kazakov)
  • General: Disable snapping to image center by default, as it can cause confusion. (bug report) (Change, by Dmitry Kazakov)
  • Calligraphy Tool: Fix following existing shape in the Calligraphy Tool. (bug report) (Change, by Dmitry Kazakov)
  • Layers: Fix "Copy into new Layer" to copy vector data when a vector shape is active. (bug report) (Change, by Dmitry Kazakov)
  • Selections: Fix the vector selection mode to not create 0px selections, and to select the canvas beforing subtracting if there is no existing selection. (bug report, CCbug report) (Change, by Dmitry Kazakov)
  • General: Add Unify Layers Color Space action. (Change, by Dmitry Kazakov)
  • Layers: Don't allow moving a mask onto a locked layer. (Change, by Maciej Jesionowski)
  • Linux: Capitalize the .AppImage file extension to match the convention expected by launchers. (bug report) (Change, by Dmitry Kazakov)
Unstable branch (5.3.0-prealpha):

Bug fixes:

  • Color Management: Update display rendering when blackpoint compensation or LCMS optimizations are toggled, not just when the display color profile is changed. (bug report) (Change, by Dmitry Kazakov)

Features:

  • Text: Implement Convert to Shape for bitmap fonts. (Change, by Wolthera van Hövell)
  • Filters: Add Fast Color Overlay filter, which overlays a solid color using a configurable blending mode. (Change, by Maciej Jesionowski)
  • Brush Engines: Add Pattern option to "Auto Invert For Eraser" mode. (Change, by Dmitry Kazakov)
  • Wide Gamut Color Selector Docker: Add option to hide the Minimal Shade Selector rows. (Change, by Wolthera van Hövell)
  • Wide Gamut Color Selector Docker: Show the Gamut Mask toolbar when the selector layout supports it. (Change, by Wolthera van Hövell)
  • Layers: Add a warning icon for layers with a different color space than the image. (Change 1, by Dmitry Kazakov, and Change 2, by Timothée Giet)
  • Pop-Up Palette: Add an option to sort the color history ring by last-used instead of by color. (bug report) (Change, by Dmitry Kazakov)
  • Export Layers Plugin: Add option to use incrementing prefix on exported layers. (wishbug report) (Change, by Ross Rosales)
Nightly Builds

Pre-release versions of Krita are built every day for testing new changes.

Get the latest bugfixes in Stable "Krita Plus" (5.2.9-prealpha): Linux - Windows - macOS (unsigned) - Android arm64-v8a - Android arm32-v7a - Android x86_64

Or test out the latest Experimental features in "Krita Next" (5.3.0-prealpha). Feedback and bug reports are appreciated!: Linux - Windows - macOS (unsigned) - Android arm64-v8a - Android arm32-v7a - Android x86_64

Categories: FLOSS Project Planets

GNU Taler news: GNU Taler 0.14 released

GNU Planet! - Sun, 2024-12-15 18:00
We are happy to announce the release of GNU Taler v0.14.
Categories: FLOSS Project Planets

Brian Okken: Testing some tidbits with pytest

Planet Python - Sun, 2024-12-15 18:00
I noticed a fun post by Ned Batchelder called Testing some tidbits. The post looks at different ways to see if a string has only 0 or 1 in it. He posted a few ways on Bluesky/Mastodon and got a bunch of replies with more ways. And then wrote a small script to check to see if they worked. It’s a fun post, and from it I learned about: cleandoc - a way to strip leading blank space and maintain code block indentation partition - splitting strings based on a substring Using | to pass imports to eval() - I don’t use eval much.
Categories: FLOSS Project Planets

Over 20 years of bug squashing

Planet KDE - Sun, 2024-12-15 13:23

The open source project I work on for the longest time is KDE and there more specific Kate.

This means I look at user bug reports for over 20 years now.

The statistics tell me our team got more than 9000 bugs since around 2001 (just for Kate, this excludes the libraries like KTextEditor that we maintain, too).

Kate Bug Statistics

That is a bit more than one bug per day for over two decades.

And as the statistics show, especially in the last years we were able to keep the open bug count down, that means we fixed a lot of them.

Given we are a small team, I think that is a nice achievement.

We not just survived over 20 years, we are still alive and kicking and not just a still compiling zombie project.

Thanks a lot to all people that are contributing to this success!

Let’s keep this up in the next year and the ones following.

Categories: FLOSS Project Planets

Freelock Blog: Automatically post to Mastodon or other remote APIs

Planet Drupal - Sun, 2024-12-15 10:00
Automatically post to Mastodon or other remote APIs Anonymous (not verified) Sun, 12/15/2024 - 07:00 Tags Content Management Social Media Mastodon BlueSky ECA Drupal Planet Automation

The ECA Helper module provides an action to make an arbitrary HTTP post to any URL. That's all that's necessary to post to Mastodon from Drupal, if you have a Mastodon account. I've been using this functionality to automatically post these advent calendar posts for the past week.

Categories: FLOSS Project Planets

Real Python: Build Enumerations of Constants With Python's Enum

Planet Python - Sun, 2024-12-15 09:00

Python’s enum module offers a way to create enumerations, a data type allowing you to group related constants. You can define an enumeration using the Enum class, either by subclassing it or using its functional API. This tutorial will guide you through the process of creating and using Python enums, comparing them to simple constants, and exploring specialized types like IntEnum, IntFlag, and Flag.

Enumerations provide benefits over simple constants by offering a structured, readable, and maintainable way to manage sets of constant values. They ensure type safety, prevent value reassignment, and facilitate iteration and member access. By learning to utilize Python’s enum types, you enhance your ability to write organized and efficient code.

By the end of this tutorial, you’ll understand that:

  • An enum in Python groups related constants in a single data type using the Enum class.
  • You create enumerations by subclassing Enum or using the module’s functional API.
  • Using Enum over simple constants provides structure, prevents reassignment, and enhances code readability.
  • Enum, IntEnum, IntFlag, and Flag differ in their support for integer operations and bitwise flags.
  • Enums can work with data types like integers or strings, boosting their flexibility.
  • You access enumeration members using dot notation, call notation, or subscript notation.
  • You can iterate over enum members using loops or the .__members__ attribute.

To follow along with this tutorial, you should be familiar with object-oriented programming and inheritance in Python.

Get Your Code: Click here to download the free sample code that you’ll use to build enumerations in Python.

Getting to Know Enumerations in Python

Several programming languages, including Java and C++, have a native enumeration or enum data type as part of their syntax. This data type allows you to create sets of named constants, which are considered members of the containing enum. You can access the members through the enumeration itself.

Enumerations come in handy when you need to define an immutable and discrete set of similar or related constant values that may or may not have semantic meaning in your code.

Days of the week, months and seasons of the year, Earth’s cardinal directions, a program’s status codes, HTTP status codes, colors in a traffic light, and pricing plans of a web service are all great examples of enumerations in programming. In general, you can use an enum whenever you have a variable that can take one of a limited set of possible values.

Python doesn’t have an enum data type as part of its syntax. Fortunately, Python 3.4 added the enum module to the standard library. This module provides the Enum class for supporting general-purpose enumerations in Python.

Enumerations were introduced by PEP 435, which defines them as follows:

An enumeration is a set of symbolic names bound to unique, constant values. Within an enumeration, the values can be compared by identity, and the enumeration itself can be iterated over. (Source)

Before this addition to the standard library, you could create something similar to an enumeration by defining a sequence of similar or related constants. To this end, Python developers often used the following idiom:

Python >>> RED, GREEN, YELLOW = range(3) >>> RED 0 >>> GREEN 1 Copied!

Even though this idiom works, it doesn’t scale well when you’re trying to group a large number of related constants. Another inconvenience is that the first constant will have a value of 0, which is falsy in Python. This can be an issue in certain situations, especially those involving Boolean tests.

Note: If you’re using a Python version before 3.4, then you can create enumerations by installing the enum34 library, which is a backport of the standard-library enum. The aenum third-party library could be an option for you as well.

In most cases, enumerations can help you avoid the drawbacks of the above idiom. They’ll also help you produce more organized, readable, and robust code. Enumerations have several benefits, some of which relate to ease of coding:

  • Allowing for conveniently grouping related constants in a sort of namespace
  • Allowing for additional behavior with custom methods that operate on either enum members or the enum itself
  • Providing quick and flexible access to enum members
  • Enabling direct iteration over members, including their names and values
  • Facilitating code completion within IDEs and editors
  • Enabling type and error checking with static checkers
  • Providing a hub of searchable names
  • Mitigating spelling mistakes when using the members of an enumeration

They also make your code robust by providing the following benefits:

  • Ensuring constant values that can’t be changed during the code’s execution
  • Guaranteeing type safety by differentiating the same value shared across several enums
  • Improving readability and maintainability by using descriptive names instead of mysterious values or magic numbers
  • Facilitating debugging by taking advantage of readable names instead of values with no explicit meaning
  • Providing a single source of truth and consistency throughout the code

Now that you know the basics of enumerations in programming and in Python, you can start creating your own enum types by using Python’s Enum class.

Creating Enumerations With Python’s Enum

Python’s enum module provides the Enum class, which allows you to create enumeration types. To create your own enumerations, you can either subclass Enum or use its functional API. Both options will let you define a set of related constants as enum members.

In the following sections, you’ll learn how to create enumerations in your code using the Enum class. You’ll also learn how to set automatically generated values for your enums and how to create enumerations containing alias and unique values. To kick things off, you’ll start by learning how to create an enumeration by subclassing Enum.

Read the full article at https://realpython.com/python-enum/ »

[ 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

Real Python: Object-Oriented Programming (OOP) in Python

Planet Python - Sun, 2024-12-15 09:00

Object-oriented programming (OOP) in Python lets you structure your code by grouping related properties and behaviors into individual objects. You create classes as blueprints and instantiate them to form objects. With OOP, you can model real-world entities and their interactions, and create complex systems with reusable components.

OOP in Python revolves around four main concepts: encapsulation, inheritance, abstraction, and polymorphism. Encapsulation bundles data with methods, inheritance lets you create subclasses, abstraction hides complex details, and polymorphism allows for different implementations.

By the end of this tutorial, you’ll understand that:

  • Object-oriented programming in Python involves structuring code into classes to model real-world entities.
  • The four key concepts of OOP in Python are encapsulation, inheritance, abstraction, and polymorphism.
  • OOP in Python is considered straightforward to learn due to its clear syntax and readability.
  • The main focus of OOP in Python involves creating classes as blueprints for objects. These objects contain data and the methods needed to manipulate that data.

You’ll explore how to define classes, instantiate classes to create objects, and leverage inheritance to build robust systems in Python.

Note: This tutorial is adapted from the chapter “Object-Oriented Programming (OOP)” in Python Basics: A Practical Introduction to Python 3.

The book uses Python’s built-in IDLE editor to create and edit Python files and interact with the Python shell, so you’ll see occasional references to IDLE throughout this tutorial. If you don’t use IDLE, you can run the example code from the editor and environment of your choice.

Get Your Code: Click here to download the free sample code that shows you how to do object-oriented programming with classes in Python 3.

Take the Quiz: Test your knowledge with our interactive “Object-Oriented Programming (OOP) in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Object-Oriented Programming (OOP) in Python

Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects.

What Is Object-Oriented Programming in Python?

Object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects.

For example, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running. Or it could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending.

Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like companies and employees or students and teachers. OOP models real-world entities as software objects that have some data associated with them and can perform certain operations.

OOP also exists in other programming languages and is often described to center around the four pillars, or four tenants of OOP:

  1. Encapsulation allows you to bundle data (attributes) and behaviors (methods) within a class to create a cohesive unit. By defining methods to control access to attributes and its modification, encapsulation helps maintain data integrity and promotes modular, secure code.

  2. Inheritance enables the creation of hierarchical relationships between classes, allowing a subclass to inherit attributes and methods from a parent class. This promotes code reuse and reduces duplication.

  3. Abstraction focuses on hiding implementation details and exposing only the essential functionality of an object. By enforcing a consistent interface, abstraction simplifies interactions with objects, allowing developers to focus on what an object does rather than how it achieves its functionality.

  4. Polymorphism allows you to treat objects of different types as instances of the same base type, as long as they implement a common interface or behavior. Python’s duck typing make it especially suited for polymorphism, as it allows you to access attributes and methods on objects without needing to worry about their actual class.

In this tutorial you’ll take a practical approach to understanding OOP in Python. But keeping these four concepts of object-oriented programming in mind may help you to remember the information that you gather.

The key takeaway is that objects are at the center of object-oriented programming in Python. In other programming paradigms, objects only represent the data. In OOP, they additionally inform the overall structure of the program.

How Do You Define a Class in Python?

In Python, you define a class by using the class keyword followed by a name and a colon. Then you use .__init__() to declare which attributes each instance of the class should have:

Python class Employee: def __init__(self, name, age): self.name = name self.age = age Copied!

But what does all of that mean? And why do you even need classes in the first place? Take a step back and consider using built-in, primitive data structures as an alternative.

Primitive data structures—like numbers, strings, and lists—are designed to represent straightforward pieces of information, such as the cost of an apple, the name of a poem, or your favorite colors, respectively. What if you want to represent something more complex?

For example, you might want to track employees in an organization. You need to store some basic information about each employee, such as their name, age, position, and the year they started working.

One way to do this is to represent each employee as a list:

Python kirk = ["James Kirk", 34, "Captain", 2265] spock = ["Spock", 35, "Science Officer", 2254] mccoy = ["Leonard McCoy", "Chief Medical Officer", 2266] Copied!

There are a number of issues with this approach.

Read the full article at https://realpython.com/python3-object-oriented-programming/ »

[ 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

Real Python: Python Classes: The Power of Object-Oriented Programming

Planet Python - Sun, 2024-12-15 09:00

Python classes form the backbone of object-oriented programming, enabling you to encapsulate data and behavior into a single entity. When you work with a Python class, you define attributes to store data and methods to perform actions. This structure allows you to model real-world objects and create organized, reusable code.

A class in Python serves as a blueprint for creating objects, which are instances of the class. You use classes when you need to encapsulate related data and functions, making your code modular and easier to manage. By defining classes, you can create multiple objects that share the same attributes and methods, while maintaining their own unique state.

In this tutorial, you’ll learn how to define and use Python classes, understand the distinction between classes and objects, and explore methods and attributes. You’ll also learn about instance and class attributes, methods, inheritance, and common pitfalls to avoid when working with classes.

By the end of this tutorial, you’ll understand that:

  • A class in Python is like a recipe for creating objects that encapsulate both data and behavior.
  • You use classes to model complex data structures and behaviors in a modular way.
  • You define classes in Python using the class keyword, and instantiate them to create objects.
  • A class is a blueprint, while an object is an instance of a class.
  • Methods define behaviors, while attributes store data within class instances.
  • Instance attributes are unique to each object, while class attributes are shared across all instances of the class.

To get the most out of this tutorial, you should know about Python variables, data types, and functions. Some experience with object-oriented programming (OOP) is also a plus. Don’t worry if you’re not an OOP expert yet. In this tutorial, you’ll learn the key concepts that you need to get started and more. You’ll also write several practical examples to help reinforce your knowledge of Python classes.

Get Your Code: Click here to download your free sample code that shows you how to build powerful object blueprints with classes in Python.

Take the Quiz: Test your knowledge with our interactive “Python Classes - The Power of Object-Oriented Programming” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Python Classes - The Power of Object-Oriented Programming

In this quiz, you'll test your understanding of Python classes. With this knowledge, you'll be able to define reusable pieces of code that encapsulate data and behavior in a single entity, model real-world objects, and solve complex problems.

Getting Started With Python Classes

Python is a multiparadigm programming language that supports object-oriented programming (OOP) through classes that you can define with the class keyword. You can think of a class as a piece of code that specifies the data and behavior that represent and model a particular type of object.

What is a class in Python? A common analogy is that a class is like the blueprint for a house. You can use the blueprint to create several houses and even a complete neighborhood. Each concrete house is an object or instance that’s derived from the blueprint.

Each instance can have its own properties, such as color, owner, and interior design. These properties carry what’s commonly known as the object’s state. Instances can also have different behaviors, such as locking the doors and windows, opening the garage door, turning the lights on and off, watering the garden, and more.

In OOP, you commonly use the term attributes to refer to the properties or data associated with a specific object of a given class. In Python, attributes are variables defined inside a class with the purpose of storing all the required data for the class to work.

Similarly, you’ll use the term methods to refer to the different behaviors that objects will show. Methods are functions that you define within a class. These functions typically operate on or with the attributes of the underlying instance or class. Attributes and methods are collectively referred to as members of a class or object.

You can write classes to model the real world. These classes will help you better organize your code and solve complex programming problems.

For example, you can use classes to create objects that emulate people, animals, vehicles, books, buildings, cars, or other objects. You can also model virtual objects, such as a web server, directory tree, chatbot, file manager, and more.

Finally, you can use classes to build class hierarchies. This way, you’ll promote code reuse and remove repetition throughout your codebase.

In this tutorial, you’ll learn a lot about classes and all the cool things that you can do with them. To kick things off, you’ll start by defining your first class in Python. Then you’ll dive into other topics related to instances, attributes, and methods.

Defining a Class in Python

To define a class, you need to use the class keyword followed by the class name and a colon, just like you’d do for other compound statements in Python. Then you must define the class body, which will start at the next indentation level:

Python Syntax class ClassName: <body> Copied!

In a class’s body, you can define attributes and methods as needed. As you already learned, attributes are variables that hold the class data, while methods are functions that provide behavior and typically act on the class data.

Note: In Python, the body of a given class works as a namespace where attributes and methods live. You can only access those attributes and methods through the class or its objects.

As an example of how to define attributes and methods, say that you need a Circle class to model different circles in a drawing application. Initially, your class will have a single attribute to hold the radius. It’ll also have a method to calculate the circle’s area:

Python circle.py import math class Circle: def __init__(self, radius): self.radius = radius def calculate_area(self): return math.pi * self.radius ** 2 Copied! Read the full article at https://realpython.com/python-classes/ »

[ 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

Real Python: Dependency Management With Python Poetry

Planet Python - Sun, 2024-12-15 09:00

Poetry is a tool for managing Python projects that simplifies dependency management. You can use Poetry to specify, install, and resolve dependencies, ensuring that you work with the correct package versions. Poetry takes advantage of a pyproject.toml file for configuration and maintains a poetry.lock file to lock dependencies, providing a consistent environment across different machines.

You should generally install Poetry system-wide using tools like pipx. You can then create a new project with poetry new or add Poetry to an existing project with poetry init. Later, use poetry add to specify a new dependency in your project and poetry install to install the listed dependencies into your environment. By understanding how to manage dependencies effectively, you ensure that your projects are reproducible and maintainable.

By the end of this tutorial, you’ll understand that:

  • Poetry is a dependency manager that ensures consistent package versions and simplifies Python project setup.
  • You can install Poetry system-wide using pipx or the official installer for better environment management.
  • Installing Poetry with pip in a project’s environment is not recommended due to potential dependency conflicts.
  • Basic Poetry CLI commands include poetry new, poetry add, poetry install, and poetry update.
  • The poetry.lock file locks dependency versions, ensuring reproducible environments.
  • You resolve dependency conflicts by updating the poetry.lock file with poetry update or poetry lock.
  • Best practices include committing the poetry.lock file to version control and avoiding system-wide package installations.

To complete this tutorial and get the most out of it, you should have a basic understanding of virtual environments, modules and packages, and pip.

While you’ll focus on dependency management in this tutorial, Poetry can also help you build a distribution package for your project. If you want to share your work, then you can use Poetry to publish your project on the Python Packaging Index (PyPI).

Free Bonus: Click here to get access to a free 5-day class that shows you how to avoid common dependency management issues with tools like Pip, PyPI, Virtualenv, and requirements files.

Take Care of Prerequisites

Before diving into the nitty-gritty of Python Poetry, you’ll take care of some prerequisites. First, you’ll read a short overview of the terminology that you’ll encounter in this tutorial. Next, you’ll install Poetry itself.

Learn the Relevant Terminology

If you’ve ever used an import statement in one of your Python scripts, then you’ve worked with modules and packages. Some of them might have been Python files you wrote on your own. Others could’ve been standard library modules that ship with Python, like datetime. However, sometimes, what Python provides isn’t enough. That’s when you might turn to external modules and packages maintained by third parties.

When your Python code relies on such external modules and packages, they become the requirements or dependencies of your project.

To find packages contributed by the Python community that aren’t part of the Python standard library, you can browse PyPI. Once you’ve found a package you’re interested in, you can use Poetry to manage and install that package in your project. Before seeing how this works, you need to install Poetry on your system.

Install Poetry on Your Computer

Poetry is distributed as a Python package itself, which means that you can install it into a virtual environment using pip, just like any other external package:

Windows PowerShell (venv) PS> python -m pip install poetry Copied! Shell (venv) $ python3 -m pip install poetry Copied!

This is fine if you just want to quickly try it out. However, the official documentation strongly advises against installing Poetry into your project’s virtual environment, which the tool must manage. Because Poetry depends on several external packages itself, you’d run the risk of a dependency conflict between one of your project’s dependencies and those required by Poetry. In turn, this could cause Poetry or your code to malfunction.

In practice, you always want to keep Poetry separate from any virtual environment that you create for your Python projects. You also want to install Poetry system-wide to access it as a stand-alone application regardless of the specific virtual environment or Python version that you’re currently working in.

There are several ways to get Poetry running on your computer, including:

  1. A tool called pipx
  2. The official installer
  3. Manual installation
  4. Pre-built system packages

In most cases, the recommended way to install Poetry is with the help of pipx, which takes care of creating and maintaining isolated virtual environments for command-line Python applications. After installing pipx, you can install Poetry by issuing the following command in your terminal window:

Windows PowerShell PS> pipx install poetry Copied! Shell $ pipx install poetry Copied!

While this command looks very similar to the one you saw previously, it’ll install Poetry into a dedicated virtual environment that won’t be shared with other Python packages.

Read the full article at https://realpython.com/dependency-management-python-poetry/ »

[ 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

libiconv @ Savannah: GNU libiconv 1.18 released

GNU Planet! - Sun, 2024-12-15 08:35

The GNU libiconv package provides the basis for character set conversion of text, for systems that don't use glibc.
It contains an implementation of the iconv() POSIX:2024 API and of the 'iconv' program, in a way that is mostly glibc compatible.

New in this release:

  • Many more transliterations, in particular also of Emoji characters.


  • The iconv_open function is now POSIX:2024 compliant: it recognizes a suffix //NON_IDENTICAL_DISCARD in the 'tocode' argument, with the effect that characters that cannot be represented in the target character set will be silently discarded. Whereas the suffix //IGNORE in the 'tocode' argument has the effect of discarding not only characters that cannot be represented in the target character set, but also invalid multibyte sequences in the input. Accordingly, the iconvctl function accepts requests ICONV_GET_DISCARD_INVALID, ICONV_SET_DISCARD_INVALID, ICONV_GET_DISCARD_NON_IDENTICAL, ICONV_SET_DISCARD_NON_IDENTICAL.


  • The iconv_open function and the iconv program now support multiple suffixes, such as //TRANSLIT//IGNORE, not only one.


  • GB18030 is now an alias for GB18030:2005. A new converter for GB18030:2022 is added. Since this encoding merely cleans up a few private-use-area mappings, you can continue to use the GB18030 converter, for backward compatibility. Its Unicode to GB18030 conversion direction has been enhanced, to help transitioning away from PUA code points.


  • When converting from/to an EBCDIC encoding, a non-standard way of converting newlines can be requested
    • at the C level, by calling iconvctl with argument ICONV_SET_FROM_SURFACE or ICONV_SET_TO_SURFACE, or
    • from the iconv program, by setting the environment variable ICONV_EBCDIC_ZOS_UNIX to a non-empty value.


  • Special support for z/OS: The iconv program adds a charset metadata tag to its output file. (Contributed by Mike Fulton.)


  • For conversions from UCS-2, UCS-4, UTF-16, UTF-32, invoking iconv(cd,NULL,NULL,...) now preserves the byte order state.
Categories: FLOSS Project Planets

This Week in KDE Apps: Gear 24.12.0 is Out

Planet KDE - Sun, 2024-12-15 07:50

Welcome to a new issue of "This Week in KDE Apps"! Every week we cover as much as possible of what's happening in the world of KDE apps.

This week aside of releasing KDE Gear 24.12.0 and Kaidan 0.10.0, we added an overview of all your data in Itinerary and polished many other apps. Some of us also meet in Berlin and organized a small KDE sprint where aside of eating some Crêpes Bretonnes, we had discussion around Itinerary, Kirigami, Powerplant and more.

KDE Itinerary Digital travel assistant

Itinerary has a new "My Data" page containing your program membership, health certificates, saved locations, travel statistics and let you export and import all the data from Itinerary. (Carl Schwan, 25.04.0 — Link)

Calculator A feature rich calculator

Fixed the "History" action not working (Joshua Goins, 25.04 — Link)

Kaidan Modern chat app for every device

Version 0.10.0 and 0.10.1 of Kaidan were released! See the release announcement for the full list of changes.

Kongress Conference companion

Show the speaker's name for each event (Volker Krause, 25.04 — Link)

Kleopatra Certificate manager and cryptography app

Improved the dialog showing results of decrypt and verify operations (Tobias Fella, 25.04, Link)

Fixed a Qt6 regression that causes the dropdown menu for certificate selection to behave in unexpected ways (Tobias Fella, 25.04 — Link)

Improved the messages showing the result when decrypting and verifying the clipboard (Tobias Fella, 25.04 — Link)

NeoChat Chat on Matrix

Fixed web shortcuts not working (Joshua Goins, 24.12.1 — Link)

Improved how colored text sent by some other clients shows up (Joshua Goins, 24.12.1 — Link)

Stop NeoChat from crashing when sending messages (Tobias Fella, 24.12.1 — Link)

Okular View and annotate documents

Improved the look of banner messages (Carl Schwan, 25.04 — Link)

PowerPlant A small app helping you to keep your plants alive

Mathis redesigned various part of Powerplant and added a tasks view. (Mathis Brucher)

Other

More Kirigami applications are now remembering their size accross restart by using KConfig.WindowStateSaver. (Nate Graham, 25.04.0 — Skanpage and Elisa)

…And Everything Else

This blog only covers the tip of the iceberg! If you’re hungry for more, check out Nate's blog about Plasma and be sure not to miss his This Week in Plasma series, where every Saturday he covers all the work being put into KDE's Plasma desktop environment.

For a complete overview of what's going on, visit KDE's Planet, where you can find all KDE news unfiltered directly from our contributors.

Get Involved

The KDE organization has become important in the world, and your time and contributions have helped us get there. As we grow, we're going to need your support for KDE to become sustainable.

You can help KDE by becoming an active community member and getting involved. Each contributor makes a huge difference in KDE — you are not a number or a cog in a machine! You don’t have to be a programmer either. There are many things you can do: you can help hunt and confirm bugs, even maybe solve them; contribute designs for wallpapers, web pages, icons and app interfaces; translate messages and menu items into your own language; promote KDE in your local community; and a ton more things.

You can also help us by donating. Any monetary contribution, however small, will help us cover operational costs, salaries, travel expenses for contributors and in general just keep KDE bringing Free Software to the world.

To get your application mentioned here, please ping us in invent or in Matrix.

Categories: FLOSS Project Planets

Pages