Feeds
Over 20 years of bug squashing
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.
Freelock Blog: Automatically post to Mastodon or other remote APIs
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.
Real Python: Build Enumerations of Constants With Python's Enum
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 PythonSeveral 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 EnumPython’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 ]
Real Python: Object-Oriented Programming (OOP) in Python
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 PythonObject-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:
-
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.
-
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.
-
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.
-
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 ]
Real Python: Python Classes: The Power of Object-Oriented Programming
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 ProgrammingIn 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 ClassesPython 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 PythonTo 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 ]
Real Python: Dependency Management With Python Poetry
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 PrerequisitesBefore 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 TerminologyIf 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 ComputerPoetry 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:
- A tool called pipx
- The official installer
- Manual installation
- 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 ]
libiconv @ Savannah: GNU libiconv 1.18 released
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.
This Week in KDE Apps: Gear 24.12.0 is Out
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 assistantItinerary 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 calculatorFixed the "History" action not working (Joshua Goins, 25.04 — Link)
Kaidan Modern chat app for every deviceVersion 0.10.0 and 0.10.1 of Kaidan were released! See the release announcement for the full list of changes.
Kongress Conference companionShow the speaker's name for each event (Volker Krause, 25.04 — Link)
Kleopatra Certificate manager and cryptography appImproved 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 MatrixFixed 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 documentsImproved the look of banner messages (Carl Schwan, 25.04 — Link)
PowerPlant A small app helping you to keep your plants aliveMathis redesigned various part of Powerplant and added a tasks view. (Mathis Brucher)
OtherMore Kirigami applications are now remembering their size accross restart by using KConfig.WindowStateSaver. (Nate Graham, 25.04.0 — Skanpage and Elisa)
…And Everything ElseThis 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 InvolvedThe 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.
LostCarPark Drupal Blog: Drupal Advent Calendar day 15 - Documentation Track
In today’s door we are looking at the Documentation Track of Drupal CMS, with some help from Amber Matz, who is working on the track.
As work progresses for the initial release of Drupal CMS, how is work progressing on documentation?
Since DrupalCon Barcelona at the end of September, we – that is Drupalize.Me trainers Joe Shindelar and myself – have been working with Lenny Moskalyk at the Drupal Association, (the Drupal CMS documentation track lead) and Pamela Barone, the Drupal CMS product lead on what documentation to Drupal CMS’ initial documentation should look like.
It’s a different process…
TagsRussell Coker: Hisense 65U80G 65″ Inch 8K ULED Android TV (2021)
I just bought a Hisense 65U80G 65″ Inch 8K ULED Android TV (2021 model) for $1,568 including delivery. I got that deal by googling refurbished 8K TVs and finding the cheapest one I could buy. Amazon and eBay didn’t have any good prices on second hand 8K TVs and new ones start at $3,000 on special. I didn’t assess how Hisense compares to other TVs, as far as I could determine there was only one model of 8K TV on sale in Australia in the price range I was prepared to pay. So I won’t review how this TV compares to other models but how refurbished TVs compare to other display options.
I bought this because the highest resolution monitor in my price range is 5120*2160 [1]. While I could get a 5128*2880 monitor for around $1,500 paying 3* the money for 33% more pixels is bad value for money. Getting 4* the pixels for under 3* the price is good value even when it’s a TV with the lower display quality that involves.
Before buying this TV I read this blog post by Daniel Lawrence about using an 8K TV as a primary monitor [2]. While he has an interesting setup with a 65″ TV on a large desk it’s not what I plan to do at this time.
My Plans for UseI don’t plan to make it a main monitor. While 5120*2160 isn’t as good as I like on my desk it’s bearable and the quality of the display is high. High resolution isn’t needed for all tasks, for example I’m writing this blog post on my laptop while watching a movie on the 8K TV.
One thing I’d like to do with the 8K TV when I get it working as a monitor is to share the screen for team programming projects. I don’t have any specific plans other than team coding projects at the moment. But it will be interesting to experiment with it when I get it working.
Technical Issues with High Resolution Monitors Hardware NeededA lot of the graphic hardware out there don’t support resolutions higher than 5120*2880. It seems that most laptops don’t support resolutions higher than that and higher resolutions than 4K are difficult. Only quite recent and high end video cards will do 8K. Apparently the RTX 2080 is one of the oldest ones that does and that’s $400 on ebay. Strangely the GPU chipset spec pages don’t list the maximum resolution and there’s the additional complication that the other chips might not support the resolutions that the GPU itself can support.
As an aside I don’t use NVidia cards for regular workstations due to reliability problems. But they are good for ML work and for special purpose systems.
Interface VersionsTo do 8K video it seems that you need HDMI 2.1 (or maybe 2.0 with 4:2:0 chroma subsampling) or DisplayPort 1.3 for 30Hz with 24bit color and 2.0 for higher refresh rates. But using a particular version of the interface doesn’t require supporting all the resolutions that it might support. This TV has HDMI 2.1 inputs, I’ve bought an adaptor cable that does DisplayPort 1.4 to HDMI 2.1 at 8K resolution. So I need a video card that does DisplayPort 1.4 or HDMI 2.1 output. That doesn’t mean that the card will work, but it could work.
It’s a pity that no-one has made a USB-C video controller that has a basic frame-buffer supporting 8K and the minimal GPU capabilities. The consensus of opinion is that no games will run well at 8K at this time so anyone using 8K resolution doesn’t need GPU power unless it’s for ML stuff.
I’m thinking of making a system that can be used as a ML server and X/Wayland server so a GPU with a decent amount of RAM and compute power would be good. I’m not particularly interested in spending $1,500+ to get a GPU that can drive a $1,568 TV. I’m looking into getting a RTX A2000 with 12G of RAM which should be adequate for ML experiments and can handle 8K@60Hz output.
I’ve ordered a DisplayPort to HDMI converter cable so if I get a DisplayPort card it will work.
Software SupportWhen I first got started with 4K monitors I had significant problems in adjusting the UI to be usable. The support for scaling software is much better now than it was then and 8K 65″ has a lower DPI than 4K 32″. So I hope this won’t be an issue.
Progress So FarMy first Hisense 8K TV stopped working properly. It would change to a mostly white screen after being used for some time. The screen would change in ways that correlate to changes in what should appear, but not in a way that was usable. It was just a different pattern of white blobs when I changed to a menu view not anything that allowed using it. I presume that this was the problem that drove a need for refurbishment as when I first got the TV it was still signed in to Google accounts for YouTube and to NetFlix.
Best Buy Electrical was good about providing a quick replacement, they took away the old TV and delivered a new one on the same visit and it’s now working well.
I’ve obtained a NVidia card that can allegedly do 8K output and a combination of cables that might be able to carry an 8K signal. Now I just need to get the NVidia drivers to not cause a kernel panic to get things to work.
- [1] https://etbe.coker.com.au/2024/07/23/more-5120×2160-monitor/
- [2] https://daniel.lawrence.lu/blog/y2023m12d15/
Related posts:
- DisplayPort and 4K The Problem Video playback looks better with a higher scan...
- More About Kogan 5120*2160 Monitor On the 18th of May I blogged about my new...
- Dell 32″ 4K Monitor and DisplayPort Switch After determining that the Philips 43″ monitor was too large...
Russell Coker: OnePlus 6 Debian
I recently got a OnePlus 6 for the purpose of running Debian, here’s the Debian wiki page about it [1]. It runs Debian nicely and the basic functions all work, but the problem I’m having now is that AldiMobile (Telstra) and KoganMobile (Vodafone) don’t enable VoLTE for that and all the Australian telcos have turned off 3G. The OnePlus 6 does VoLTE with Chinese SIMs so the phone itself can do it.
The OnePlus 6 was never sold in Australia by the telcos, so they are all gray-market imports which aren’t designed by OnePlus to work in Australia. Until recently that wasn’t a problem, but now that the 3G network has been turned off we need VoLTE and OnePlus didn’t include that in the OS. Reddit has documentation on how to fix this but it has to be done on Android [2]. So I had to go back from Mobian to Android to get VoLTE (and VoWifi) working and then install Mobian again.
For people with similar issues Telstra has a page for checking which phones are supported [3], it’s the only way to determine if it’s the phone or the network that makes VoLTE not work – Android isn’t informative about such things. Telstra lists the OP6 as a suitable phone.
Now after doing this I still can’t get the OP6 working for phone calls on Phosh or PlasmaMobile and I’m not sure why. I’m going to give the PinePhone Pro another go and see if it now works better. In the past I had problems with the PinePhonePro battery discharging too fast, charging too slowly, and having poor call quality [4]. The battery discharge issue should be at least alleviated by some of the changes in the Plasma 6 code that’s now in Debian/Unstable.
I’ve also been lent a PinePhone (non-pro) and been told that it will have better battery life in many situations. I’ll do some tests of that. The PinePhonePro isn’t capable of doing the convergence things I was hoping to do so the greater RAM and CPU power that it has aren’t as relevant as they otherwise would be.
I have a vision for how phones should work. I am not discouraged by the Librem 5, PinePhonePro, Note 9, and OnePlus 6 failing in various ways to do what I hoped for. I will eventually find a phone that I can get working well enough.
- [1] https://wiki.debian.org/InstallingDebianOn/OnePlus/OnePlus6
- [2] https://tinyurl.com/29lo6srp
- [3] https://tinyurl.com/23ta7pjf
- [4] https://etbe.coker.com.au/2023/10/11/pinephone-status/
Related posts:
- PineTime Status Since my last blog post about the PineTime [1] I...
- Samsung Galaxy Note 9 Review After the VoLTE saga [1] and the problems with battery...
- PinePhonePro First Impression Hardware I received my PinePhone Pro [1] on Thursday, it...
Real Python: Build Command-Line Interfaces With Python's argparse
When building Python command-line interfaces (CLI), Python’s argparse module offers a comprehensive solution. You can use argparse to create user-friendly command-line interfaces that parse arguments and options directly from the command line. This tutorial guides you through organizing CLI projects, adding arguments and options, and customizing your CLI’s behavior with argparse.
You’ll also learn about setting up command-line argument parsers, parsing arguments, and implementing advanced features like subcommands and mutually exclusive argument groups. By understanding how argparse handles errors and messages, you can create robust and intuitive CLIs for your Python applications.
By the end of this tutorial, you’ll understand that:
- Command-line interfaces enable interaction with applications through terminals.
- You can create CLIs in Python using the standard library argparse module.
- argparse parses command-line arguments and generates help messages.
- You can customize CLIs with argparse by defining argument types and actions.
- Subcommands and mutually exclusive groups enhance CLI functionality.
- Error handling and exit statuses are crucial for robust CLI applications.
To get the most out of this tutorial, you should be familiar with Python programming, including concepts such as object-oriented programming, script development and execution, and Python packages and modules. It’ll also be helpful if you’re familiar with general concepts and topics related to using a command line or terminal.
Get Your Code: Click here to download the free sample code that you’ll use to build command-line interfaces with argparse.
Take the Quiz: Test your knowledge with our interactive “Build Command-Line Interfaces With Python's argparse” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Build Command-Line Interfaces With Python's argparseIn this quiz, you'll test your understanding of creating command-line interfaces (CLIs) in Python using the argparse module. This knowledge is essential for creating user-friendly command-line apps, which are common in development, data science, and systems administration.
Getting to Know Command-Line InterfacesSince the invention of computers, humans have always needed and found ways to interact and share information with these machines. The information exchange has flowed among humans, computer software, and hardware components. The shared boundary between any two of these elements is generically known as an interface.
In software development, an interface is a special part of a given piece of software that allows interaction between components of a computer system. When it comes to human and software interaction, this vital component is known as the user interface.
You’ll find different types of user interfaces in programming. Probably, graphical user interfaces (GUIs) are the most common today. However, you’ll also find apps and programs that provide command-line interfaces (CLIs) for their users. In this tutorial, you’ll learn about CLIs and how to create them in Python.
Command-Line Interfaces (CLIs)Command-line interfaces allow you to interact with an application or program through your operating system command line, terminal, or console.
To understand command-line interfaces and how they work, consider this practical example. Say that you have a directory called sample containing three sample files. If you’re on a Unix-like operating system, such as Linux or macOS, go ahead and open a command-line window or terminal in the parent directory and then execute the following command:
Shell $ ls sample/ hello.txt lorem.md realpython.md Copied!The ls Unix command lists the files and subdirectories contained in a target directory, which defaults to the current working directory. The above command call doesn’t display much information about the content of sample. It only displays the filenames on the screen.
Note: If you’re on Windows, then you’ll have an ls command that works similarly to the Unix ls command. However, in its plain form, the command displays a different output:
Windows PowerShell PS> ls .\sample\ Directory: C:\sample Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 11/10/2022 10:06 AM 88 hello.txt -a--- 11/10/2022 10:06 AM 2629 lorem.md -a--- 11/10/2022 10:06 AM 429 realpython.md Copied!The PowerShell ls command issues a table containing detailed information on every file and subdirectory under your target directory. So, the upcoming examples won’t work as expected on Windows systems.
Suppose you want richer information about your directory and its content. In that case, you don’t need to look around for a program other than ls because this command has a full-featured command-line interface with a useful set of options that you can use to customize the command’s behavior.
For example, go ahead and execute ls with the -l option:
Shell $ ls -l sample/ total 24 -rw-r--r--@ 1 user staff 83 Aug 17 22:15 hello.txt -rw-r--r--@ 1 user staff 2609 Aug 17 22:15 lorem.md -rw-r--r--@ 1 user staff 428 Aug 17 22:15 realpython.md Copied!The output of ls is quite different now. The command displays much more information about the files in sample, including permissions, owner, group, date, and size. It also shows the total space that these files use on your computer’s disk.
Note: To get a detailed list of all the options that ls provides as part of its CLI, go ahead and run the man ls command in your command line or terminal.
This richer output results from using the -l option, which is part of the Unix ls command-line interface and enables the detailed output format.
Commands, Arguments, Options, Parameters, and SubcommandsThroughout this tutorial, you’ll learn about commands and subcommands. You’ll also learn about command-line arguments, options, and parameters, so you should incorporate these terms into your tech vocabulary:
Read the full article at https://realpython.com/command-line-interfaces-python-argparse/ »[ 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 ]
Real Python: YAML: The Missing Battery in Python
YAML is a portable and widely used data serialization format. Unlike the more compact JSON or verbose XML formats, YAML emphasizes human readability with block indentation, which should be familiar to most Python programmers. While Python comes with batteries included, it lacks built-in support for YAML. Still, you can read and write YAML documents in Python by installing a third-party library, such as PyYAML.
PyYAML allows you to serialize and deserialize Python data types, as well as custom objects, to and from YAML. It also provides ways to safely handle YAML data from untrusted sources. PyYAML is a popular choice for relatively simple use cases. However, you might want to explore alternatives like ruamel.yaml for YAML 1.2 compliance or StrictYAML for schema validation.
By the end of this tutorial, you’ll understand that:
- YAML stands for YAML Ain’t Markup Language, emphasizing its focus on data representation rather than document markup.
- YAML is often used for configuration and serialization due to its human-readable syntax.
- Python doesn’t support YAML natively, unlike the JSON and XML formats. You need to install a third-party library to work with YAML in Python programs.
- PyYAML is arguably the most popular YAML library for Python due to its simplicity.
- Alternatives to PyYAML include ruamel.yaml and StrictYAML, which offer more features.
To get the most out of this tutorial, you should be familiar with object-oriented programming in Python and know how to create a class. If you’re ready to jump in, then you can follow the link below to get the source code for the examples that you’ll code in this tutorial:
Get Your Code: Click here to download the free sample code you’ll use to work with YAML in Python.
Taking a Crash Course in YAMLIn this section, you’re going to learn the basic facts about YAML, including its uses, syntax, and some of its unique and powerful features. If you’ve worked with YAML before, then you can skip ahead and continue reading from the next section, which covers using YAML in Python.
Historical ContextYAML, which rhymes with camel, is a recursive acronym that stands for YAML Ain’t Markup Language because it’s not a markup language! Interestingly enough, the original draft for the YAML specification defined the language as Yet Another Markup Language, but later the current backronym was adopted to more accurately describe the language’s purpose.
An actual markup language, such as Markdown or HTML, lets you annotate text with formatting or processing instructions intermixed with your content. Markup languages are, therefore, primarily concerned with text documents, whereas YAML is a data serialization format that integrates well with common data types native to many programming languages. There’s no inherent text in YAML, only data to represent.
YAML was originally meant to simplify Extensible Markup Language (XML), but in reality, it has a lot more in common with JavaScript Object Notation (JSON). In fact, it’s a superset of JSON.
Even though XML was initially designed to be a metalanguage for creating markup languages for documents, people quickly adopted it as the standard data serialization format. The HTML-like syntax of angle brackets made XML look familiar. Suddenly, everyone wanted to use XML as their configuration, persistence, or messaging format.
As the first kid on the block, XML dominated the scene for many years. It became a mature and trusted data interchange format and helped shape new concepts like building interactive web applications. After all, the letter X in AJAX, a technique for getting data from the server without reloading the page, stands for none other than XML.
Ironically, it was AJAX that ultimately led to XML’s decline in popularity. The verbose, complex, and redundant XML syntax wasted a lot of bandwidth when data was sent over the network. Parsing XML documents in JavaScript was slow and tedious because of XML’s fixed document object model (DOM), which wouldn’t match the application’s data model. The community finally acknowledged that they’d been using the wrong tool for the job.
That’s when JSON entered the picture. It was built from the ground up with data serialization in mind. Web browsers could parse it effortlessly because JSON is a subset of JavaScript, which they already supported. Not only was JSON’s minimalistic syntax appealing to developers, but it also made porting to other platforms easier than XML did. To this day, JSON remains the slimmest, fastest, and most versatile textual data interchange format on the Internet.
YAML came into existence the same year as JSON, and by pure coincidence, it was almost a complete superset of JSON on the syntactical and semantic levels. Starting from YAML 1.2, the format officially became a strict superset of JSON, meaning that every valid JSON document also happens to be a YAML document.
In practice, however, the two formats look different, as the YAML specification puts more emphasis on human readability by adding a lot more syntactic sugar and features on top of JSON. As a result, YAML is more applicable to configuration files edited by hand rather than as a transport layer.
Comparison With XML and JSONIf you’re familiar with XML or JSON, then you might be wondering what YAML brings to the table. All three are major data interchange formats, which share some overlapping features. For example, they’re all text based and more or less human readable. At the same time, they differ in many respects, which you’ll find out next.
Note: There are other, popular textual data formats like TOML, which the new build system in Python is based on. Currently, only external packaging and dependency management tools like Poetry can read TOML, but since Python 3.11 there’s a TOML parser in the standard library.
Common binary data serialization formats you’d find in the wild include Google’s Protocol Buffers and Apache’s Avro.
Now have a look at a sample document expressed in all three data formats but representing the same person. You can click to expand the collapsible sections and reveal data serialized in those formats:
XMLShow/Hide
XML <?xml version="1.0" encoding="UTF-8" ?> <person firstName="John" lastName="Doe"> <dateOfBirth>1969-12-31</dateOfBirth> <married>true</married> <spouse> <person firstName="Jane" lastName="Doe"> <dateOfBirth/> <!- This is a comment --> </person> </spouse> </person> Copied!JSONShow/Hide
JSON { "person": { "dateOfBirth": "1969-12-31", "firstName": "John", "lastName": "Doe", "married": true, "spouse": { "dateOfBirth": null, "firstName": "Jane", "lastName": "Doe" } } } Copied!YAMLShow/Hide
YAML %YAML 1.2 --- person: dateOfBirth: 1969-12-31 firstName: John lastName: Doe married: true spouse: dateOfBirth: null # This is a comment firstName: Jane lastName: Doe Copied! Read the full article at https://realpython.com/python-yaml/ »[ 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 ]
Real Python: Primer on Python Decorators
Python decorators allow you to modify or extend the behavior of functions and methods without changing their actual code. When you use a Python decorator, you wrap a function with another function, which takes the original function as an argument and returns its modified version. This technique provides a simple way to implement higher-order functions in Python, enhancing code reusability and readability.
You can use decorators in various practical scenarios, such as logging, enforcing access control, caching results, or measuring execution time. To create a custom decorator, define a function that takes another function as an argument, creates a nested wrapper function, and returns the wrapper. When applying a decorator, you place @decorator on the line before the function definition.
By the end of this tutorial, you’ll understand that:
- Python decorators allow you to wrap a function with another function to extend or modify its behavior without altering the original function’s code.
- Practical use cases for decorators include logging, enforcing access control, caching results, and measuring execution time.
- Custom decorators are written by defining a function that takes another function as an argument, defines a nested wrapper function, and returns the wrapper.
- Multiple decorators can be applied to a single function by stacking them, one per line, before the function definition.
- The order of decorators impacts the final output, as each decorator wraps the next, influencing the behavior of the decorated function.
You can find all the examples from this tutorial by downloading the accompanying materials below:
Get Your Code: Click here to download the free sample code that shows you how to create and use Python decorators.
Free Bonus: Click here to get access to a free "The Power of Python Decorators" guide that shows you three advanced decorator patterns and techniques you can use to write cleaner and more Pythonic programs.
Decorators Cheat Sheet: Click here to get access to a free three-page Python decorators cheat sheet that summarizes the techniques explained in this tutorial.
Decorators Q&A Transcript: Click here to get access to a 25-page chat log from our Python decorators Q&A session in the Real Python Community Slack where we discussed common decorator questions.
Take the Quiz: Test your knowledge with our interactive “Decorators” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
DecoratorsIn this quiz, you'll revisit the foundational concepts of what Python decorators are and how to create and use them.
Python FunctionsIn order to understand decorators, you must first understand some finer points of how functions work. There are many aspects to functions, but in the context of decorators, a function returns a value based on the given arguments. Here’s a basic example:
Python >>> def add_one(number): ... return number + 1 ... >>> add_one(2) 3 Copied!In general, functions in Python may also have side effects rather than just turning an input into an output. The print() function is an example of this: it returns None while having the side effect of outputting something to the console. However, to understand decorators, it’s enough to think about functions as tools that turn given arguments into values.
First-Class ObjectsIn functional programming, you work almost entirely with pure functions that don’t have side effects. While not a purely functional language, Python supports many functional programming concepts, including treating functions as first-class objects.
This means that functions can be passed around and used as arguments, just like any other object like str, int, float, list, and so on. Consider the following three functions:
Python greeters.py def say_hello(name): return f"Hello {name}" def be_awesome(name): return f"Yo {name}, together we're the awesomest!" def greet_bob(greeter_func): return greeter_func("Bob") Copied!Here, say_hello() and be_awesome() are regular functions that expect a name given as a string. The greet_bob() function, however, expects a function as its argument. You can, for example, pass it the say_hello() or the be_awesome() function.
To test your functions, you can run your code in interactive mode. You do this with the -i flag. For example, if your code is in a file named greeters.py, then you run python -i greeters.py:
Python >>> greet_bob(say_hello) 'Hello Bob' >>> greet_bob(be_awesome) 'Yo Bob, together we're the awesomest!' Copied!Note that greet_bob(say_hello) refers to two functions, greet_bob() and say_hello, but in different ways. The say_hello function is named without parentheses. This means that only a reference to the function is passed. The function isn’t executed. The greet_bob() function, on the other hand, is written with parentheses, so it will be called as usual.
This is an important distinction that’s crucial for how functions work as first-class objects. A function name without parentheses is a reference to a function, while a function name with trailing parentheses calls the function and refers to its return value.
Inner FunctionsIt’s possible to define functions inside other functions. Such functions are called inner functions. Here’s an example of a function with two inner functions:
Read the full article at https://realpython.com/primer-on-python-decorators/ »[ 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 ]
Real Python: Sorting a Python Dictionary: Values, Keys, and More
Sorting a Python dictionary involves organizing its key-value pairs in a specific order. To sort a Python dictionary by its keys, use the sorted() function combined with .items(). This approach returns a list of tuples sorted by keys, which you can convert back to a dictionary using the dict() constructor. Sorting by values requires specifying a sort key using a lambda function or itemgetter().
You can sort a Python dictionary in descending order by setting the reverse argument of the sorted() function to True. Sorting dictionaries with non-comparable keys or values can be challenging, but you can manage it by providing default values or using a custom sort key.
By the end of this tutorial, you’ll understand that:
- You can sort a dictionary by its keys using sorted() with .items() and dict().
- To sort by values, you use sorted() with a key function like lambda or itemgetter().
- Sorting in descending order is possible by setting reverse=True in sorted().
- For non-comparable keys or values, you use default values or custom sort keys.
- Python dictionaries can’t be sorted in-place, so you need to create a new sorted dictionary.
Read on to learn how to effectively sort dictionaries using these techniques and the strategic implications of choosing the right data structure for your key-value data. But first, you’ll learn some foundational knowledge that will help you understand how to sort a dictionary in Python.
Free Download: Click here to download the code that you’ll use to sort key-value pairs in this tutorial.
Rediscovering Dictionary Order in PythonBefore Python 3.6, dictionaries were inherently unordered. A Python dictionary is an implementation of the hash table, which is traditionally an unordered data structure.
As a side effect of the compact dictionary implementation in Python 3.6, dictionaries started to conserve insertion order. From 3.7, that insertion order has been guaranteed.
If you wanted to keep an ordered dictionary as a data structure before compact dictionaries, then you could use OrderedDict from the collections module. Similar to the modern compact dictionary, it also keeps insertion order, but neither type of dictionary sorts itself.
Another alternative for storing an ordered key-value pair data is to store the pairs as a list of tuples. As you’ll see later in the tutorial, using a list of tuples could be the best choice for your data.
An essential point to understand when sorting dictionaries is that even though they conserve insertion order, they’re not considered a sequence. A dictionary is like a set of key-value pairs, and sets are unordered.
Dictionaries also don’t have much reordering functionality. They’re not like lists, where you can insert elements at any position. In the next section, you’ll explore the consequences of this limitation further.
Understanding What Sorting a Dictionary Really MeansBecause dictionaries don’t have much reordering functionality, when sorting a dictionary, it’s rarely done in-place. In fact, there are no methods for explicitly moving items in a dictionary.
If you wanted to sort a dictionary in-place, then you’d have to use the del keyword to delete an item from the dictionary and then add it again. Deleting and then adding again effectively moves the key-value pair to the end.
The OrderedDict class has a specific method to move an item to the end or the start, which may make OrderedDict preferable for keeping a sorted dictionary. However, it’s still not very common and isn’t very performant, to say the least.
The typical method for sorting dictionaries is to get a dictionary view, sort it, and then cast the resulting list back into a dictionary. So you effectively go from a dictionary to a list and back into a dictionary. Depending on your use case, you may not need to convert the list back into a dictionary.
Note: Sorted dictionaries aren’t a very common pattern. You’ll explore more about that topic later in the tutorial.
With those preliminaries out of the way, you’ll get to sorting dictionaries in the next section.
Sorting Dictionaries in PythonIn this section, you’ll be putting together the components of sorting a dictionary so that, in the end, you can master the most common way of sorting a dictionary:
Python >>> people = {3: "Jim", 2: "Jack", 4: "Jane", 1: "Jill"} >>> # Sort by key >>> dict(sorted(people.items())) {1: 'Jill', 2: 'Jack', 3: 'Jim', 4: 'Jane'} >>> # Sort by value >>> dict(sorted(people.items(), key=lambda item: item[1])) {2: 'Jack', 4: 'Jane', 1: 'Jill', 3: 'Jim'} Copied!Don’t worry if you don’t understand the snippets above—you’ll review it all step-by-step in the following sections. Along the way, you’ll learn how to use the sorted() function with sort keys, lambda functions, and dictionary constructors.
Using the sorted() Function Read the full article at https://realpython.com/sort-python-dictionary/ »[ 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 ]
Real Python: The Walrus Operator: Python's Assignment Expressions
Python’s walrus operator (:=) allows you to assign values to variables as part of an expression. It can simplify your code by combining assignment and evaluation in a single statement. You use it to streamline constructs like list comprehensions, loops, and conditionals, making your code more concise and readable. The walrus operator is particularly useful when you want to avoid repetitive function calls or calculations.
The walrus operator, also known as an assignment expression, differs from regular assignments by returning the assigned value, enabling inline assignments within expressions. Regular assignment (=) doesn’t return a value, which helps prevent common programming errors.
By the end of this tutorial, you’ll understand that:
- The walrus operator (:=) is a syntax for assigning variables within expressions in Python.
- Assignment expressions use the walrus operator in Python.
- You can use the walrus operator to streamline code, such as in loops or conditionals.
- Assignment expressions return the assigned value, unlike regular assignments.
- Regular assignments don’t return values to prevent unintended behavior and bugs.
- Best practices for the walrus operator include using it for clarity and efficiency without overcomplicating code.
Understanding the walrus operator will enhance your ability to write efficient and concise Python code, especially when dealing with complex conditions and loops.
Get Your Code: Click here to download the free sample code that shows you how to use Python’s walrus operator.
Take the Quiz: Test your knowledge with our interactive “The Walrus Operator: Python's Assignment Expressions” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
The Walrus Operator: Python's Assignment ExpressionsIn this quiz, you'll test your understanding of Python's walrus operator. This operator was introduced in Python 3.8, and understanding it can help you write more concise and efficient code.
Walrus Operator FundamentalsFirst, look at some different terms that programmers use to refer to this new syntax. You’ve already seen a few in this tutorial.
The := operator is officially known as the assignment expression operator. During early discussions, it was dubbed the walrus operator because the := syntax resembles the eyes and tusks of a walrus lying on its side. You may also see the := operator referred to as the colon equals operator. Yet another term used for assignment expressions is named expressions.
Hello, Walrus!To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code:
Python 1>>> walrus = False 2>>> walrus 3False 4 5>>> (walrus := True) 6True 7>>> walrus 8True Copied!Line 1 shows a traditional assignment statement where the value False is assigned to walrus. Next, on line 5, you use an assignment expression to assign the value True to walrus. After both lines 1 and 5, you can refer to the assigned values by using the variable name walrus.
You might be wondering why you’re using parentheses on line 5, and you’ll learn why the parentheses are needed later on in this tutorial.
Note: A statement in Python is a unit of code. An expression is a special statement that can be evaluated to some value.
For example, 1 + 2 is an expression that evaluates to the value 3, while number = 1 + 2 is an assignment statement that doesn’t evaluate to a value. Although running the statement number = 1 + 2 doesn’t evaluate to 3, it does assign the value 3 to number.
In Python, you often see simple statements like return statements and import statements, as well as compound statements like if statements and function definitions. These are all statements, not expressions.
There’s a subtle—but important—difference between the two types of assignments with the walrus variable. An assignment expression returns the value, while a traditional assignment doesn’t. You can see this in action when the REPL doesn’t print any value after walrus = False on line 1 but prints out True after the assignment expression on line 5.
You can see another important aspect about walrus operators in this example. Though it might look new, the := operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient and can sometimes communicate the intent of your code more clearly.
Now you have a basic idea of what the := operator is and what it can do. It’s an operator used in assignment expressions, which can return the value being assigned, unlike traditional assignment statements. To get deeper and really learn about the walrus operator, continue reading to see where you should and shouldn’t use it.
ImplementationLike most new features in Python, assignment expressions were introduced through a Python Enhancement Proposal (PEP). PEP 572 describes the motivation for introducing the walrus operator, the details of the syntax, and examples where the := operator can be used to improve your code.
This PEP was originally written by Chris Angelico in February 2018. Following some heated discussion, PEP 572 was accepted by Guido van Rossum in July 2018.
Since then, Guido announced that he was stepping down from his role as benevolent dictator for life (BDFL). Since early 2019, the Python language has been governed by an elected steering council instead.
The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.
Motivation Read the full article at https://realpython.com/python-walrus-operator/ »[ 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 ]
Kushal Das: Open Source talk at KTH computer science students organization
Last Tuesday, during lunch hours I had a talk at KTH computer science students' organization. The topic was Open Source and career. My main goal was tell the attendees that contribution size does not matter, but continuing contributing to various projects can change someone's life and career in a positive way. I talked about the history of the Free Software movement and Open Source. I also talked a bit about Aaron Swartz and asked the participants to watch the documentary The Internet's Own Boy. Some were surprised to hear about Sunet's Open Source work.
There were around 70 people and few people later message how they think about contribution after my talk. The best part was one student who messaged next day and said that he contributed one small patch to a project.
I also told them about PyLadies Stockholm and other local efforts from various communities. There was also a surprising visit of the #curl channel on IRC, thanks to bagder and icing :)
LostCarPark Drupal Blog: Drupal Advent Calendar day 14 - Multilingual and Concurrent Editing
Welcome to another door of the Starshot focused Drupal Advent Calendar. This might be that day when you open the door and there’s an odd-shaped piece of chocolate, and you’re not quite sure what it’s supposed to represent. Starshot, like any large project, has some tracks that have advanced more than others, and it’s only natural that some tracks are still at an early stage. Today we are taking a brief look at a couple of those tracks, along with some tasty bonus information.
Multilingual TrackDrupal has excellent support for translation and multilingual websites in core. However, it can be…
TagsThis Week in Plasma: Better fractional scaling
This week's headliner change is something that I think will make a lot of people happy: better fractional scaling! Vlad and Xaver have been hard at work to snap everything to the screen's pixel grid, with the effect that using a fractional scale factor now results in a lot less blurriness as well as no more gaps between windows and their shadows. You'll see it in the screenshot below (which was taken at 175% scale) but the effects are subtly better everywhere. Really great stuff!
And lots more too, of course:
Notable New FeaturesAt very high zoom levels, KWin's Zoom effect switches to a sharp pixel-perfect representation and overlays a grid on top of the screen. This makes it easy to see how individual pixels look relative to other ones, which can be useful for artists and designers. (Vlad Zahorodnii, 6.3.0. Link)
KWin now offers you the option to prefer screen color accuracy at the expense of some system performance, should that be your preference (e.g. if you're a digital artist and not a gamer). (Xaver Hugl, 6.3.0. Link)
If the feature to be able to maximize a window horizontally or vertically by double-clicking on one of its edges doesn't agree with you, you can now disable it. (Vlad Zahorodnii, 6.3.0. Link)
Notable UI ImprovementsLanded a huge overhaul of how fractional scale factors are handled in KWin. Now it makes an effort to always snap things to the screen's pixel grid, greatly reducing blurriness and visual gaps everywhere. I've been using these patches with a 175% scale factor for a week, and everything looks just fantastic! (Vlad Zahorodnii and Xaver Hugl, 6.3.0. Link)
On login, Plasma panels now appear on screen only after their contents have been fully loaded. (Niccolò Venerandi, 6.3.0. Link)
Notable Bug FixesFixed a nasty bug affecting people using the X11 session that could sometimes cause the lock screen to be all black. (Philip Müller, 6.2.5. Link)
Fixed a specific instance where you could end up with a black screen when wiggling the pointer while the screen is about to lock. (David Redondo, 6.2.5 Link)
Fixed a visual bug in Discover that caused UI elements to overlap on expanded list items on the Updates page. (Aleix Pol Gonzalez, 6.2.5. Link)
Fixed the application menu appearing in a wrong position when opened via the window titlebar with Qt 6.8. (David Redondo, 6.2.5. Link)
Fixed a bug that could cause windows on a screen that gets disconnected to become lost and stuck in an off-screen position in the new screen arrangement. (Vlad Zahorodnii and Xaver Hugl, 6.3.0. Link)
You can no longer slightly break the Overview effect's Desktop Grid view by dragging windows outside of the screen area. (Niccolò Venerandi, 6.3.0. Link)
Dragging an image from the clipboard to the desktop now shows the normal drop menu, rather than creating an empty Media Frame widget. (Fushan Wen, 6.3.0. Link)
Non-rectangular-region screenshots taken in Spectacle and copied to the clipboard can now be pasted into Dolphin as expected. (Fushan Wen, 6.3.0. Link)
Standalone (not in System Tray) "Power and Battery" and "Brightness and Color" widgets once again work properly, as expected. (Jakob Petsovits, 6.3.0. Link)
Fixed a bug in the Breeze Dark icon theme that caused places/folder icons to remain colorful at small sizes where symbolic icons are normally expected. (David Redondo, Frameworks 6.9. Link)
Plasma and lots of apps no longer crash when your /etc/fstab file contains any loop mounts in it. (Nicolas Fella, Frameworks 6.10. Link)
Other bug information of note:
- 2 Very high priority Plasma bugs (down from 3 last week). Current list of bugs
- 32 15-minute Plasma bugs (down from 35 last week). Current list of bugs
- 104 KDE bugs of all kinds fixed over the last week. Full list of bugs
Ported the clipboard to use a standard SQLite database, rather than its own internal custom format. This improves reliability, support for saving many data types, and memory efficiency especially with images. (Fushan Wen, 6.3.0. Link)
How You Can HelpKDE has become important in the world, and your time and contributions have helped us get there. As we grow, we need your support to keep KDE sustainable.
Thankfully, thousands of you have stepped up in the past week to do just that financially, donating a record-breaking amount of money to KDE e.V., which is just incredible, awe-inspiring even.
So that's a great way to help out. But if you've got more time than money or want to make a difference more directly, then you can help KDE by becoming an active community member and getting involved somehow. 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. Many other opportunities exist:
- Triage and confirm bug reports, maybe even identify their root cause
- Contribute designs for wallpapers, icons, and app interfaces
- Design and maintain websites
- Translate user interface text items into your own language
- Promote KDE in your local community
- …And a ton more things!
To get a new Plasma feature or a bugfix mentioned here, feel free to push a commit to the relevant merge request on invent.kde.org.