Feeds
Qt Creator 15 - CMake Update
Here are the new CMake features and fixes in Qt Creator 15:
Python Bytes: #414 Because we are not monsters
Zato Blog: HL7 FHIR Integrations in Python
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 serversOutgoing 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
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 serversTo 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 useThe "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 securityOutgoing 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.
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
Handling incorrect warnings and a limited functionality in QML Code Editor in Qt Creator 14.0 and 15.0
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.
Russ Allbery: Review: Finders
Review: Finders, by Melissa Scott
Series: Firstborn, Lastborn #1 Publisher: Candlemark & Gleam Copyright: 2018 ISBN: 1-936460-87-4 Format: Kindle Pages: 409Finders 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
Krita Monthly Update - Edition 21
Welcome to the @Krita-promo team's November 2024 development and community update.
Development Report Community Bug Hunt EndedThe 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 ResultsFor 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 NowFor 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 2024Seven 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 KritaKrita 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 ChangesNotable 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)
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)
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
GNU Taler news: GNU Taler 0.14 released
Brian Okken: Testing some tidbits with pytest
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 ]