Feeds

Martin Fitzpatrick: Getting started with VS Code for Python

Planet Python - Mon, 2023-09-11 13:39

Setting up a working development environment is the first step for any project. Your development environment setup will determine how easy it is to develop and maintain your projects over time. That makes it important to choose the right tools for your project. This article will guide you through how to set up Visual Studio Code, which is a popular free-to-use, cross-platform code editor developed by Microsoft, in order to develop Python applications.

Visual Studio Code is not to be confused with Visual Studio, which is a separate product also offered by Microsoft. Visual Studio is a fully-fledged IDE that is mainly geared towards Windows application development using C# and the .NET Framework.

Setup a Python environment

In case you haven't already done this, Python needs to be installed on the development machine. You can do this by going to python.org and grabbing the specific installer for either Windows or macOS. Python is also available for installation via Microsoft Store on Windows devices.

Make sure that you select the option to Add Python to PATH during installation (via the installer).

If you are on Linux, you can check if Python is already installed on your machine by typing python3 --version in a terminal. If it returns an error, you need to install it from your distribution's repository. On Ubuntu/Debian, this can be done by typing sudo apt install python3. Both pip (or pip3) and venv are distributed as separate packages on Ubuntu/Debian and can also be installed by typing sudo apt install python3-pip python3-venv.

Setup Visual Studio Code

First, head over to to code.visualstudio.com and grab the installer for your specific platform.

If you are on a Raspberry Pi (with Raspberry Pi OS), you can also install VS Code by simply typing sudo apt install code. On Linux distributions that support Snaps, you can do it by typing sudo snap install code --classic.

Once VS Code is installed, head over to the Extensions tab in the sidebar on the left by clicking on it or by pressing CTRL+SHIFT+X. Search for the 'Python' extension published by Microsoft and click on Install.

The Extensions tab in the left-hand sidebar.

Usage and Configuration

Now that you have finished setting up VS Code, you can go ahead and create a new Python file. Remember that the Python extension only works if you open a .py file or have selected the language mode for the active file as Python.

To change the language mode for the active file, simply press CTRL+K once and then press M after releasing the previous keys. This kind of keyboard shortcut is called a chord in VS Code. You can see more of them by pressing CTRL+K CTRL+S (another chord).

The Python extension in VS Code allows you to directly run a Python file by clicking on the 'Play' button on the top-right corner of the editor (without having to type python file.py in the terminal).

You can also do it by pressing CTRL+SHIFT+P to open the Command Palette and running the > Python: Run File in Terminal command.

Finally, you can configure VS Code's settings by going to File > Preferences > Settings or by pressing CTRL+COMMA. In VS Code, each individual setting has an unique identifier which you can see by clicking on the cog wheel that appears to the left of each setting and clicking on 'Copy Setting ID'. This ID is what will be referred to while talking about a specific setting. You can also search for this ID in the search bar under Settings.

Linting and Formatting Support (Optional)

Linters make it easier to find errors and check the quality of your code. On the other hand, code formatters help keep the source code of your application compliant with PEP (Python Enhancement Proposal) standards, which make it easier for other developers to read your code and collaborate with you.

For VS Code to provide linting support for your projects, you must first install a preferred linter like flake8 or pylint.

bash pip install flake8

Then, go to Settings in VS Code and toggle the relevant setting (e.g. python.linting.flake8Enabled) for the Python extension depending on what you installed. You also need to make sure that python.linting.enabled is toggled on.

A similar process must be followed for code formatting. First, install something like autopep8 or black.

bash pip install autopep8

You then need to tell VS Code which formatter to use by modifying python.formatting.provider and toggle on editor.formatOnSave so that it works without manual intervention.

If pip warns that the installed modules aren't in your PATH, you may have to specify the path to their location in VS Code (under Settings). Follow the method described under Working With Virtual Environments to do that.

Now, when you create a new Python file, VS Code automatically gives you a list of Problems (CTRL+SHIFT+M) in your program and formats the code on saving the file.

Identified problems in the source code, along with a description and line/column numbers.

You can also find the location of identified problems from the source overview on the right hand, inside the scrollbar.

Working With Virtual Environments

Virtual environments are a way of life for Python developers. Most Python projects require the installation of external packages and modules (via pip). Virtual environments allow you to separate one project's packages from your other projects, which may require a different version of those same packages. Hence, it allows all those projects to have the specific dependencies they require to work.

The Python extension makes it easier for you by automatically activating the desired virtual environment for the in-built terminal and Run Python File command after you set the path to the Python interpreter. By default, the path is set to use the system's Python installation (without a virtual environment).

To use a virtual environment for your project/workspace, you need to first make a new one by opening a terminal (View > Terminal) and typing python -m venv .venv. Then, you can set the default interpreter for that project by opening the Command Palette (CTRL+SHIFT+P) and selecting > Python: Select Interpreter.

You should now either close the terminal pane in VS Code and open a new one or type source .venv/bin/activate into the existing one to start using the virtual environment. Then, install the required packages for your project by typing pip install <package_name>.

VS Code, by default, looks for tools like linters and code formatters in the current Python environment. If you don't want to keep installing them over and over again for each new virtual environment you make (unless your project requires a specific version of that tool), you can specify the path to their location under Settings in VS Code. - flake8 - python.linting.flake8Path - autopep8 - python.formatting.autopep8Path

To find the global location of these packages on macOS and Linux, type which flake8 and which autopep8 in a terminal. If you are on Windows, you can use where <command_name>. Both these commands assume that flake8 and autopep8 are in your PATH.

Understanding Workspaces in VS Code

VS Code has a concept of Workspaces. Each 'project folder' (or the root/top folder) is treated as a separate workspace. This allows you to have project-specific settings and enable/disable certain extensions for that workspace. It is also what allows VS Code to quickly recover the UI state (e.g. files that were previously kept open) when you open that workspace again.

In VS Code, each workspace (or folder) has to be 'trusted' before certain features like linters, autocomplete suggestions and the in-built terminal are allowed to work.

In the context of Python projects, if you tend to keep your virtual environments outside the workspace (where VS Code is unable to detect it), you can use this feature to set the default path to the Python interpreter for that workspace. To do that, first Open a Folder (CTRL+K CTRL+O) and then go to File > Preferences > Settings > Workspace to modify python.defaultInterpreterPath.

Setting the default interpreter path for the workspace.

In VS Code settings you can search for settings by name using the bar at the top.

You can also use this approach to do things like use a different linter for that workspace or disable the code formatter for it. The workspace-specific settings you change are saved in a .vscode folder inside that workspace, which you can share with others.

If your VS Code is not recognizing libraries you are using in your code, double check the correct interpreter is being used. You can find which Python version you're using on the command line by running which python or which python3 on macOS/Linux, or where python or where python3 on Windows.

Working With Git in VS Code (Optional)

Using Version Control is required for developing applications. VS Code does have in-built support for Git but it is pretty barebones, not allowing much more than tracking changes that you have currently made and committing/pushing those changes once you are done.

For the best experience, it is recommended to use the GitLens extension. It lets you view your commit history, check who made the changes and much more. To set it up, you first need to have Git set up on your machine (go here) and then install GitLens from the Extensions tab in the sidebar on the left. You can now use those Git-related features by going to the Git tab in the sidebar (CTRL+SHIFT+G).

There are more Git-related extensions you could try as well, like Git History and GitLab Workflow. Give them a whirl too!

Community-driven & open source alternatives

While VS Code is open source (MIT-licensed), the distributed versions include some Microsoft-specific proprietary modifications, such as telemetry (app tracking). If you would like to avoid this, there is also a community-driven distribution of Visual Studio Code called VSCodium that provides freely-licensed binaries without telemetry.

Due to legal restrictions, VSCodium is unable to use the official Visual Studio Marketplace for extensions. Instead, it uses a separate vendor neutral, open source marketplace called Open VSX Registry. It doesn't have every extension, especially proprietary ones, and some are not kept up-to-date but both the Python and GitLens extensions are available on it.

You can also use the open source Jedi language server for the Python extension, rather than the bundled Pylance language server/extension, by configuring the python.languageServer setting. You can then completely disable Pylance by going to the Extensions tab. Note that, if you are on VSCodium, Jedi is used by default (as Pylance is not available on Open VSX Registry) when you install the Python extension.

Conclusion

Having the right tools and making sure they're set up correctly will greatly simplify your development process. While Visual Studio starts as a simple tool, it is flexible and extendable with plugins to suit your own preferred workflow. In this tutorial we've covered the basics of setting up your environment, and you should now be ready to start developing your own applications with Python!

Categories: FLOSS Project Planets

Martin Fitzpatrick: PyQt6, PySide6, PyQt5 and PySide2 Books -- updated for 2022!

Planet Python - Mon, 2023-09-11 13:39

Hello! Today I have released new digital editions of my PyQt5, PyQt6, PySide2 and PySide6 book Create GUI Applications with Python & Qt.

This update adds over 200 pages of Qt examples and exercises - the book is now 780 pages long! - and continues to be updated and extended. The latest additions include:

  • Built-in dialogs, including QMessageBox and QFileDialog
  • Working with multiple windows, cross-window communication
  • Using QThreadPool.start() to execute Python functions
  • Long-running threads with QThread
  • Using custom widgets in Qt Designer
  • Recurring & single shot timers
  • Managing data files, working with paths
  • Packaging with PyInstaller on Windows, macOS & Linux
  • Creating distributable installers on Windows, macOS & Linux

This update marks the 5th Edition of the book.

As always, if you've previously bought a copy of the book you get these updates for free! Just go to the downloads page and enter the email you used for the purchase. If you have problems getting this update just get in touch.

Enjoy!

Categories: FLOSS Project Planets

Martin Fitzpatrick: DiffCast: Hands-free Python Screencast Creator

Planet Python - Mon, 2023-09-11 13:39

Programming screencasts are a popular way to teach programming and demo tools. Typically people will open up their favorite editor and record themselves tapping away. But this has a few problems. A good setup for coding isn't necessarily a good setup for video -- with text too small, a window too big, or too many distractions. Typing code in live means mistakes, which means more time editing or confusion for the people watching.

DiffCast eliminates that, automatically generating screencasts from Python source files you prepare ahead of time.

DiffCast is written in Python with PyQt6. Source code available on Github

Given the following Python source files:

python print('Hello, world!') python name = input('What is your name?\n') print(f'Hello, {name}!') python friends = ['Emelia', 'Jack', 'Bernardina', 'Jaap'] name = input('What is your name?\n') if name in friends: print(f'Hello, {name}!') else: print("I don't know you.") python friends = ['Emelia', 'Jack', 'Bernardina', 'Jaap'] while True: name = input('What is your name?\n') if name in friends: print(f'Hello, {name}!') else: print("I don't know you.") friends.append(name)

DiffCast will generate the following screencast (editor can be captured separately).

The editor view is configured to be easily readable in video, without messing with your IDE settings. Edits happen at a regular speed, without mistakes, making them easy to follow. Each diffcast is completely reproducible, with the same files producing the same output every time. You can set defined window sizes, or remove the titlebar to record.

Designed for creating reproducible tutoring examples, library demos or demonstrating code to a class. You can also step forwards and backwards through each file manually, using the control panel.

Finally, you can write out edits to a another file, and show the file location in a file listing for context. Run the intermediate files to demonstrate the effect of the changes.

DiffCast is open source (GPL licensed) & free to use. For bug reports, feature requests see the Github project.

Categories: FLOSS Project Planets

Martin Fitzpatrick: PySide6 tutorial now available

Planet Python - Mon, 2023-09-11 13:39

Hello! With the release of Qt6 versions of PyQt and PySide the course was getting a little crowded. So, today I've split the PySide tutorials into their own standalone PySide2 course and PySide6 course.

The tutorials have all been updated for PySide2 & PySide6, with some additional improvements based on the latest editions of the book.

This first update includes the following PySide tutorials --

Getting started creating Python GUIs with PySide Using Qt Designer with PySide Extended UI features in PySide Multi threading PySide applications & QProcess Qt Model Views Pyside plotting & graphics with Matplotlib/PyQtGraph Bitmap graphics and custom widgets Packaging (PySide2 only)

That's all for now!

You can also still access the PyQt5 tutorial and PyQt6 tutorial.

Categories: FLOSS Project Planets

Martin Fitzpatrick: PyQt6 Book now available: Create GUI Applications with Python &amp; Qt6

Planet Python - Mon, 2023-09-11 13:39

Hello! Today I have released the first PyQt6 edition of my book Create GUI Applications, with Python & Qt6.

This update follows the 4th Edition of the PyQt5 book updating all the code examples and adding additional PyQt6-specific detail. The book contains 600+ pages and 200+ complete code examples taking you from the basics of creating PyQt applications to fully functional apps.

Enjoy!

Categories: FLOSS Project Planets

Martin Fitzpatrick: PySide6 Book now available: Create GUI Applications with Python &amp; Qt6

Planet Python - Mon, 2023-09-11 13:39

Hello! This morning I released the first Qt6 edition of my PySide book Create GUI Applications, with Python & Qt6.

This update follows the 4th Edition of the PySide2 book updating all the code examples and adding additional PySide6-specific detail. The book contains 600+ pages and 200+ complete code examples taking you from the basics of creating PySide applications to fully functional apps.

If you have any questions or difficulty getting hold of this update, just get in touch.

Enjoy!

Categories: FLOSS Project Planets

Martin Fitzpatrick: Using MicroPython and uploading libraries on Raspberry Pi Pico

Planet Python - Mon, 2023-09-11 13:39

MicroPython is an implementation of the Python 3 programming language, optimized to run on microcontrollers. It's one of the options available for programming your Raspberry Pi Pico and a nice friendly way to get started with microcontrollers.

MicroPython can be installed easily on your Pico, by following the instructions on the Raspberry Pi website (click the Getting Started with MicroPython tab and follow the instructions).

After that point you might get a bit stuck. The Pico documentation covers connecting to the Pico from a Pi, so if you're wanting to code from your own computer you'll need something else. One option is the Thonny IDE which you use to write and upload code to your Pico. It's got a nice friendly interface for working with Python.

But if you don't want to change your IDE, or want a way to communicate with your Pico from the command line? You're in luck: there is a simple tool for accessing the MicroPython REPL on your Pico and uploading custom Python scripts or libraries you may wish to use: rshell

In this tutorial I'll take you through working with MicroPython in rshell, coding live and uploading custom scripts to your Pico.

Installing rshell

Rshell itself is built on Python (not MicroPython) and can be installed and run locally on your main machine. You can install it like any other Python library.

bash python -m pip install rshell

Unfortunately, the current version of rshell does not always play nicely with the Raspberry Pico. If you have problems you can install a fixed version in the pico branch from the rshell repository. You can install this directly from Github with the following --

bash python -m pip install https://github.com/dhylands/rshell/archive/pico.zip

This will download the latest version of the pico branch (as a .zip) and install this in your Python environment.

Once installed, you will have access to a new command line tool rshell.

The rshell interface

To use rshell from the command line, enter rshell at your command prompt. You will see a welcome message and the prompt will turn green, to indicate you're in rshell mode.

The rshell interface on Windows 10

The rshell interface on macOS

If previous pip install worked but the rshell command doesn't work, then you may have a problem with your Python paths.

To see the commands available in rshell, enter help and press Enter.

python help Documented commands (type help <topic>): ======================================== args cat connect date edit filesize help mkdir rm shell boards cd cp echo exit filetype ls repl rsync Use the exit command to exit rshell.

You can exit rshell at any time by entering exit or pressing Ctrl-C. Once exited the prompt will turn white.

The basic file operation commands are shown below.

  • cd <dirname> change directory
  • cp <from> <to> copy a file
  • ls list current directory
  • rm <filename> remove (delete) a file
  • filesize <filename> give the size of a file in bytes

If you type ls and press enter you will see a listing of your current folder on your host computer. The same goes for any of the other file operations, until we've connect a board and opened it's file storage -- so be careful! We'll look at how to connect to a MicroPython board and work with the files on it next.

Connecting to your Pico with rshell

Enter boards to see a list of MicroPython boards connected to your computer. If you don't have any connected boards, you'll see the message No boards connected.

If your board isn't connected plug your Pico in now. You can use the connect command to connect to the board, but for that you'll need to know which port it is on. Save yourself some effort and just restart rshell to connect automatically. To do this, type exit and press Enter (or press Ctrl-C) to exit and then restart rshell by entering rshell again at the prompt.

If a board is connected when you start rshell you will see something like the following...

python C:\Users\Gebruiker>rshell Connecting to COM4 (buffer-size 128)... Trying to connect to REPL connected

Or an equivalent on macOS...

python Martins-Mac: ~ mfitzp$ rshell Connecting to /dev/cu.usbmodem0000000000001 (buffer-size 128) Trying to connect to REPL connected

...which shows you've connected to the MicroPython REPL on the Raspberry Pi Pico. Once connected the boards command will return some information about the connected board, like the following.

python pyboard @ COM4 connected Epoch: 1970 Dirs:

The name on the left is the type of board (Pico appears as pyboard) and connected port (here COM4). The label at the end Dirs: will list any files on the Pico -- currently none.

Starting a REPL

With the board connected, you can enter the Pico's REPL by entering the repl command. This will return something like the following

python repl Entering REPL. Use Control-X to exit. > MicroPython v1.14 on 2021-02-14; Raspberry Pi Pico with RP2040 Type "help()" for more information. >>> >>>

You are now writing Python on the Pico! Try entering print("Hello!") at the REPL prompt.

python MicroPython v1.14 on 2021-02-14; Raspberry Pi Pico with RP2040 Type "help()" for more information. >>> >>> print("Hello!") Hello!

As you can see, MicroPython works just like normal Python. If you enter help() and press Enter, you'll get some basic help information about MicroPython on the Pico. Helpfully, you also get a small reference to how the pins on the Pico are numbered and the different ways you have to control them.

python Type "help()" for more information. >>> help() Welcome to MicroPython! For online help please visit https://micropython.org/help/. For access to the hardware use the 'machine' module. RP2 specific commands are in the 'rp2' module. Quick overview of some objects: machine.Pin(pin) -- get a pin, eg machine.Pin(0) machine.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p methods: init(..), value([v]), high(), low(), irq(handler) machine.ADC(pin) -- make an analog object from a pin methods: read_u16() machine.PWM(pin) -- make a PWM object from a pin methods: deinit(), freq([f]), duty_u16([d]), duty_ns([d]) machine.I2C(id) -- create an I2C object (id=0,1) methods: readfrom(addr, buf, stop=True), writeto(addr, buf, stop=True) readfrom_mem(addr, memaddr, arg), writeto_mem(addr, memaddr, arg) machine.SPI(id, baudrate=1000000) -- create an SPI object (id=0,1) methods: read(nbytes, write=0x00), write(buf), write_readinto(wr_buf, rd_buf) machine.Timer(freq, callback) -- create a software timer object eg: machine.Timer(freq=1, callback=lambda t:print(t)) Pins are numbered 0-29, and 26-29 have ADC capabilities Pin IO modes are: Pin.IN, Pin.OUT, Pin.ALT Pin pull modes are: Pin.PULL_UP, Pin.PULL_DOWN Useful control commands: CTRL-C -- interrupt a running program CTRL-D -- on a blank line, do a soft reset of the board CTRL-E -- on a blank line, enter paste mode For further help on a specific object, type help(obj) For a list of available modules, type help('modules')

You can run help() in the REPL any time you need a reminder.

While we're here, lets flash the LED on the Pico board.

Enter the following at the REPL prompt...

python from machine import Pin led = Pin(25, Pin.OUT) led.toggle()

Every time you call led.toggle() the LED will toggle from ON to OFF or OFF to ON.

To exit the REPL at any time press Ctrl-X

Uploading a file

MicroPython comes with a lot of built-in support for simple devices and communication protocols -- enough to build some quite fun things just by hacking in the REPL. But there are also a lot of libraries available for working with more complex hardware. To use these, you need to be able to upload them to your Pico! Once you can upload files, you can also edit your own code locally on your own computer and upload it from there.

To keep things simple, lets create our own "library" that adjusts the brightness of the LED on the Pico board -- exciting I know. This library contains a single function ledon which accepts a single parameter brightness between 0 and 65535.

python from machine import Pin, PWM led = PWM(Pin(25)) def ledon(brightness=65535): led.duty_u16(brightness)

Don't worry if you don't understand it, we'll cover how this works later. The important bit now is getting this on your Pico.

Take the code above and save it in a file named picoled.py on your main computer, in the same folder you're executing rshell from. We'll upload this file to the Pico next.

Start rshell if you are not already in it -- look for the green prompt. Enter boards at the prompt to get a list of connected boards.

bash pyboard @ COM4 connected Epoch: 1970 Dirs:

To see the directory contents of the pyboard device, you can enter:

bash ls /pyboard

You should see nothing listed. The path /pyboard works like a virtual folder meaning you can copy files to this location to have the uploaded to your Pico. It is only available by a pyboard is connected. To upload a file, we copy it to this location. Enter the following at the prompt.

bash cp picoled.py /pyboard/picoled.py

After you press Enter you'll see a message confirming the copy is taking place

python C:\Users\Gebruiker> cp picoled.py /pyboard Copying 'C:\Users\Gebruiker/picoled.py' to '/pyboard/picoled.py' ...

Once the copy is complete, run boards again at the prompt and you'll see the file listed after the Dirs: section, showing that it's on the board.

bash C:\Users\Gebruiker> boards pyboard @ COM4 connected Epoch: 1970 Dirs: /picoled.py /pyboard/picoled.py

You can also enter ls /pyboard to see the listing directly.

bash C:\Users\Gebruiker> ls /pyboard picoled.py

If you ever need to upload multiple files, just repeat the upload steps until everything is where it needs to be. You can always drop in and out of the REPL to make sure things work.

Using uploaded libraries

Now we've uploaded our library, we can use it from the REPL. To get to the MicroPython REPL enter the repl command in rshell as before. To use the library we uploaded, we can import it, just like any other Python library.

python MicroPython v1.14 on 2021-02-14; Raspberry Pi Pico with RP2040 Type "help()" for more information. >>> >>> import picoled >>> picoled.ledon(65535) >>> picoled.ledon(30000) >>> picoled.ledon(20000) >>> picoled.ledon(10000)

Or to pulse the brightness of the LED...

python >>> import picoled >>> import time >>> while True: ... for a in range(0, 65536, 10000): ... picoled.ledon(a) ... time.sleep(0.1) Auto-running Python

So far we've been uploading code and running it manually, but once you start building projects you'll want your code to run automatically.

When it starts, MicroPython runs two scripts by default: boot.py and main.py, in that order. By uploading your own script with the name main.py it will run automatically every time the Raspberry Pico starts.

Let's update our "library" to become an auto script that runs at startup. Save the following code to a script named main.py.

python from machine import Pin, PWM from time import sleep led = PWM(Pin(25)) def ledon(brightness=65535): led.duty_u16(brightness) while True: for a in range(0, 65536, 10000): ledon(a) sleep(0.1)

In rshell run the command to copy the file to main.py on the board.

bash cp main.py /pyboard/main.py

Don't copy this file to boot.py -- the loop will block the REPL startup and you won't be able to connect to your Pico to delete it again! If you do this, use the Resetting Flash memory instructions to clear your Pico. You will need to re-install MicroPython afterwards.

Once the main.py file is uploaded, restart your Pico -- either unplug and re-plug it, or press Ctrl-D in the REPL -- and the LED will start pulsing automatically. The script will continue running until it finishes, or the Pico is reset. You can replace the main.py script at any time to change the behavior, or delete it with.

bash rm /pyboard/main.py What's next?

Now you can upload libraries to your Pico you can get experimenting with the many MicroPython libraries that are available.

If you're looking for some more things to do with MicroPython on your Pico, there are some MicroPython examples available from Raspberry Pi themselves, and also the MicroPython documentation for language/API references.

Categories: FLOSS Project Planets

FSF News: FSF job opportunity: Operations assistant

GNU Planet! - Mon, 2023-09-11 10:43
The Free Software Foundation (FSF), a Massachusetts 501(c)(3) charity with a worldwide mission to protect and promote computer-user freedom, seeks a motivated and organized Boston-based individual to be our full-time operations assistant.
Categories: FLOSS Project Planets

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

Planet Python - Mon, 2023-09-11 10:00

Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. In this tutorial, you’ll learn the basics of object-oriented programming in Python.

Conceptually, objects are like the components of a system. Think of a program as a factory assembly line of sorts. At each step of the assembly line, a system component processes some material, ultimately transforming raw material into a finished product.

An object contains data, like the raw or preprocessed materials at each step on an assembly line. In addition, the object contains behavior, like the action that each assembly line component performs.

In this tutorial, you’ll learn how to:

  • Define a class, which is like a blueprint for creating an object
  • Use classes to create new objects
  • Model systems with class inheritance

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.

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.

Note: You can also check out the Python Basics: Object-Oriented Programming video course to reinforce the skills that you’ll develop in this section of the tutorial.

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:

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

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:

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

There are a number of issues with this approach.

First, it can make larger code files more difficult to manage. If you reference kirk[0] several lines away from where you declared the kirk list, will you remember that the element with index 0 is the employee’s name?

Second, it can introduce errors if employees don’t have the same number of elements in their respective lists. In the mccoy list above, the age is missing, so mccoy[1] will return "Chief Medical Officer" instead of Dr. McCoy’s age.

A great way to make this type of code more manageable and more maintainable is to use classes.

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

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

Categories: FLOSS Project Planets

Stack Abuse: Maximum and Minimum Values for Integers in Python

Planet Python - Mon, 2023-09-11 09:31
Introduction

Integers are one of the fundamental data types that you'll encounter. They're used in just about every application and understanding their limits can be crucial for avoiding errors or even optimizing your code. In this Byte, we'll peak into the world of integers, exploring how to find their maximum and minimum values and why you might need to know these values.

Integers in Python

Python is a dynamically typed language, which means that the Python interpreter infers the type of an object at runtime. This is different from statically-typed languages where you have to explicitly declare the type of all variables. For integers, Python provides the int type. Here's a simple example:

x = 10 print(type(x)) # <class 'int'>

This is a basic usage of an integer in Python. But what if we try to assign a really, really large value to an integer?

x = 10**100 print(x) # 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 print(type(x)) # <class 'int'>

Even with such a large number, Python still treats it as an integer! This is because Python's int type can handle large integers, limited only by the amount of memory available.

Why Would You Need to Know Max/Min Integer Values?

So you might be wondering why you'd ever need to know the maximum or minimum values of an integer in Python. After all, Python's int type can handle pretty large numbers, right? Well, while it's true that Python's int type can handle large numbers, there are still cases where knowing the maximum or minimum values can be useful.

For instance, when interfacing with C libraries or when dealing with file formats or network protocols that have specific integer size requirements, it's important to know the limits of your integers. Also, knowing the limits of your integers can be useful for debugging and optimization.

Another common use for min/max values is in certain algorithms. Let's say you're trying to find the minimum number in a set. For the sake of the initial comparison, you'd likely want to set your min value to the highest number possible so that the first value you compare it to will be lower. In a language like JavaScript, we'd use:

let min = Infinity;

But unfortunately, Python doesn't have a built-in way to do that.

How to Find Maximum/Minimum Integer Values

In Python, the sys module provides a constant, sys.maxsize, that represents the maximum integer that can be used for things like indexing Python's built-in data structures. Here's how you can access it:

import sys print(sys.maxsize) # 9223372036854775807

Note: The value of sys.maxsize can vary between platforms and Python versions, but it's generally 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.

But what about the minimum value? Python doesn't have a built-in way to find the minimum value of an integer. However, since Python's integers can be negative, the minimum value is simply -sys.maxsize - 1.

import sys print(-sys.maxsize - 1) # -9223372036854775808 Finding the Min/Max Values for Floats, Including Infinity

Floating-point numbers in Python have their limits, just like integers. However, these limits are fairly large and suffice for most applications. Knowing these limits becomes essential when you're dealing with expansive datasets or high-precision calculations.

You can find the maximum and minimum float values using the sys.float_info object, which is part of Python's sys module. This object provides details about the floating-point type, including its maximum and minimum representable positive finite values.

import sys print("Max finite float value:", sys.float_info.max) print("Min positive finite float value:", sys.float_info.min)

When you execute this code, you'll likely see output similar to the following:

Max finite float value: 1.7976931348623157e+308 Min positive finite float value: 2.2250738585072014e-308

Note: Again, the exact values may differ based on your system's architecture and the version of Python you are using.

Interestingly, Python also provides a way to represent positive and negative infinity for float types, which effectively serve as bounds beyond the finite limits. You can define these infinities using float('inf') for positive infinity and float('-inf') for negative infinity.

Here's a quick example:

positive_infinity = float('inf') negative_infinity = float('-inf') print("Positive Infinity:", positive_infinity) print("Negative Infinity:", negative_infinity)

Running this code snippet will display:

Positive Infinity: inf Negative Infinity: -inf

These special float values can come in handy for initializing variables in algorithms, where you need a value guaranteed to be higher or lower than any other number.

Python 2 vs Python 3

When it comes to integer and float limits, there's a significant difference between Python 2 and Python 3.

In Python 2, there were two types of integers: int and long. The int type does have a limit, but the long type could handle arbitrarily large numbers. In Python 3, however, these two types were merged into a single int type, which can handle arbitrarily large numbers just like the long type in Python 2.

As for floats, there's no difference between Python 2 and Python 3. Both versions use the IEEE 754 standard for floating-point arithmetic, which defines the max and min values we discussed in the previous section.

Conclusion

While Python's dynamic typing system makes it easy to work with numbers, it's still important to know these limits, especially when dealing with very large numbers or high-precision calculations. I hope this Byte has shed some light on a topic that often goes unnoticed but is still important in Python programming.

Categories: FLOSS Project Planets

Mike Driscoll: PyDev of the Week: Jelle Zijlstra

Planet Python - Mon, 2023-09-11 08:30

This week, we welcome Jelle Zijlstra as our PyDev of the Week! Jelle is a core developer of the Python programming language. If you’d like to see what exactly Jelle is working on, you should check out his GitHub profile, Quora, or the Python Packaging Index.

Let’s take a few moments to get to know Jelle better!

Can you tell us a little about yourself (hobbies, education, etc):

I grew up in the Netherlands wanting to be a biologist, but decided to go to the United States for college. Then I took a computer science class, took a few more, and decided that software engineering offered better career prospects than biology. I still graduated with a degree in biology, but found a job as a software engineer.

Still, biology remains one of my main hobbies: I maintain a big database of biological nomenclature at https://hesperomys.com. I started out doing this in spreadsheets, and now it is a SQLite database. Learning to program has been hugely valuable for building up a high-quality, interconnected database.

Before the pandemic I used to walk much of the way to work, but then I was stuck at home, so I decided to go on walks anyway to exercise. That quickly spiraled into ridiculously long walks around the San Francisco Bay Area, up to 57 miles in a day. I write about my walks at https://walkingbayarea.quora.com/.

But the reason you’re interviewing me is my open source work. At my job a few years ago I got to start a new service that was going to be in Python 3, so I got to use shiny new tools like typing and asyncio. I ran into some minor issues with typing, started contributing to the relevant open source projects, and got sucked in. Now I help maintain several important parts of the Python ecosystem, including typing-extensions, typeshed, Black, mypy, and CPython.

Why did you start using Python?

The first language I learned in college was C. I’m still not sure whether I think C is a good first language to teach to students, but it’s definitely been valuable in giving me an understanding of how basic concepts such as pointers and memory work. Later in that class, we did a little bit of web programming in PHP. PHP isn’t a great language, but for my personal programming projects (such as maintaining my mammal database), it was still a better fit than C—no segfaults and much more library support. But I had to use Python in another class, and I quickly realized it was a lot better than PHP. Then I started a job mostly using Python, so it remained my main language.

What other programming languages do you know and which is your favorite?

When I interviewed for my current job, during each interview I picked the language that felt like the best fit for the question, and at the end of the day it turned out I had used a different language in each interview! I think it was C, Python, JavaScript, and OCaml. More recently, the main non-Python languages I’ve used have been TypeScript and C++, plus a bit of Swift. I think languages are valuable when they teach you something new about programming. OCaml was the most valuable language I learned in college because it taught me a completely new style of programming. Among languages I have dabbled in since, Haskell and Rust have been most useful.

What projects are you working on now?

My most recent major open-source contribution has been implementing PEP 695 for Python 3.12, which is coming out in October. It’s a major syntactic change that makes it a lot easier to write generics in Python. I wrote up a detailed account of the implementation at https://jellezijlstra.github.io/pep695.

At my job, I am now working on Poe, an AI chat app. Outside of work, I’ve been focusing recently on my mammal database instead of open-source software.

Which Python libraries are your favorite (core or 3rd party)?

typing. It’s been an invaluable tool to keep our huge Python codebase at work manageable.

How did you get into doing core Python development?

I attended a CPython sprint at PyCon in Portland and Cleveland before the pandemic and contributed a few things; for example, you can thank me for `@contextlib.asynccontextmanager`. However, the CPython core always felt a little remote and hard to get into, with the unusual workflow at the time (e.g., using Gerrit) and long release cycle. But then one day, Guido van Rossum emailed me to ask whether I was interested in becoming a core dev, so I said yes and after spending a few months becoming more familiar with the workflow (which is now a lot less unusual), I was voted in as a core dev. Guido asked me because at the time he was basically maintaining typing.py by himself, and obviously he is very busy. Now, we have several other people helping out in that area.

What are some new features in Python that you’re excited about?

I’m excited about the new syntax for generics and type aliases that I helped get into Python 3.12. Longer term, Python 3.13 should ship with deferred evaluation of annotations (PEP 649), which will make a lot of code that uses type annotations more ergonomic. We’re also likely to ship support for inline TypedDict types, another nice usability improvement.

Thanks so much for doing the interview, Jelle!

The post PyDev of the Week: Jelle Zijlstra appeared first on Mouse Vs Python.

Categories: FLOSS Project Planets

QtWayland 6.6 Brings Robustness Through Compositor Handoffs

Planet KDE - Mon, 2023-09-11 08:00

Every release has a killer feature. Qt 6.6 features the opposite - staying alive. This blog post describes work to make Qt clients more robust and seemlessly migrate between compositors, providing resistance against compositor crashes and more.

Prologue

Right now if you restart pulseaudio your sound might cut out, restart NetworkManager and you lose your wifi, restart an X11 window manager and your decorations disappear.

But within a second it's all back to normal exactly where you left off with everything recovering fine.

This isn't true for display servers. If X11 restarts you're back at the login prompt. All drafts lost, games unsaved, work wasted.

Past

For X11 this was unfixable; clients relied on memory stored by the Xserver, they made synchronous calls that were expected to return values, and multiple clients talked to multple clients.

This was a real problem in my early days of Linux, X11 would lock up frequently enough that most distributions had a shortcut key to restart the server and send you back to the login prompt.

It's less of an issue now as X11 has been in a lengthy period of feature freeze.

Present

Wayland makes it possible to fix all this. Memory allocations are client side, all operations are async, all protocols are designed that the compositor always has complete control.

Yet the current user-facing state is considerably worse:

  • Compositors and displays servers are now the same process, doubling the space for errors

  • Compositors are typically extensible with 3rd party plugins and scripts

  • The wayland security model means the compositor absorbs even more functions from global shortcuts to screencasting and input-method handling

  • The wayland ecosystem is not in a period of feature freeze with wayland protocols constantly evolving to cover missing features and new ideas.

    Even if there was a perfect compositor:

  • 40% of kwin's crash bug reports are either upstream or downstream causes

  • The current compositor developer experience is limited with developers having to relogin and restart their apps and development setup just to test their latest changes.

Plan

The solution for this? Instead of exiting when the compositor closes, simply...don't!

If we could connect to a new compositor we just need to send the right amount of information to bring it in sync and notify the application code of any changes to bring this in sync.

For Qt applications all this information is handled in the backend, in the Wayland Qt Platform Abstraction (QPA).

Qt already has to handle screens and input devices being removed, clipboards being revoked and drag and drops cancelled. Supporting a whole reset isn't introducing any new work, we just have to trigger all of these actions at once, then reconnect to the newly restored compositor and restore our contents.

Applications already have to support all of these events too as well as handle callbacks to redraw buffers. There's no changes needed at an application code level, it's all done as transparently as possible.

Handling OpenGL is a challenge, right now we don't have a way to keep that alive. Fortunately we put in lots of effort previously in supporting GPU resets throughout the Qt stack. The QtWayland backend fakes to the applications that a GPU reset has occured through the Qt abstractions.

For the majority of applications including all QtQuick users this happens automatically and flawlessly, building on the work that we put in previously.

Whilst the overall concepts might sound invasive, the final merge-request to support all of this for all Qt applications was fewer lines than supporting middle-click paste.

Almost no work needs doing on the compositor side. For a compositor there's no difference between a new client, and a client that was running previously reconnecting. The only big change we made within Kwin is having a helper process so the whole process can be seemless and race-free.

Proof

Path Forward

This post is about Qt, but the world is bigger than that. Not only does this technique work here, but we have pending patches for GTK, SDL and even XWayland, with key parts of SDL merged but disabled already.

The challenge for the other toolkits is we can't use the same OpenGL trick as Qt. They either lack GPU reset handling either at a toolkit level or within the applications.

Supporting OpenGL requires new infrastructure. We've tried from the start to get some infrastructure in place to allow this.It was clear that proposing library changes for client reconnection support was an uphill battle whilst being unproven in the wild.

After Qt6 is rolled out to a wider audience and shown to work reliably, we'll refocus efforts on pushing upstream changes to the other platforms.

Potential Perks

This isn't just about crashes. If support becomes mainstream there will be additional opportunities:

  • We can easily upgrade to new features without having to log out and back. This is one of the reasons why kwin development is happening at such a rapid pace in recent months. We're not having to test in fake nested sessions or waste time logging in and setting up between changes.

  • We can support multihead, running different compositors per group of outputs and move seemlessly between them.

  • It's feasible to switch between compositors at runtime. With the application handling the reconnect logic, they can easily handle the case where compositor feature sets vary.

  • Checkpoint restore in userspace, being able to suspend your application to disk and then pick up where you left off like nothing happened. It could never work for X applications, but with wayland reconnect support we can make it work.

Participating

More information about the long term goal this can be found at the kwin wiki, or each out to me directly if you want to add support.

Discuss this at discuss.kde.org.

Categories: FLOSS Project Planets

Electric Citizen: 2023 Twin Cities Drupal Camp is Here!

Planet Drupal - Mon, 2023-09-11 04:09

This week we're excited for the return of an in-person, Twin Cities Drupal Camp!

After several years of pandemic-related postponements, we're finally ready to begin the 10th annual conference, dedicated to all things Drupal and hosted in the Minneapolis-St.Paul area.

Categories: FLOSS Project Planets

Talk Python to Me: #429: Taming Flaky Tests

Planet Python - Mon, 2023-09-11 04:00
We write tests to show us when there are problems with our code. But what if there are intermittent problems with the tests themselves? That can be big hassle. In this episode, we have Gregory Kapfhammer and Owain Parry on the show to share their research and advice for taming flaky tests.<br/> <br/> <strong>Links from the show</strong><br/> <br/> <div><b>Gregory Kapfhammer</b>: <a href="https://www.gregorykapfhammer.com" target="_blank" rel="noopener">gregorykapfhammer.com</a><br/> <b>Owain Parry on Twitter</b>: <a href="https://twitter.com/oparry9" target="_blank" rel="noopener">@oparry9</a><br/> <b>Radon</b>: <a href="https://pypi.org/project/radon/" target="_blank" rel="noopener">pypi.org</a><br/> <b>pytest-xdist</b>: <a href="https://github.com/pytest-dev/pytest-xdist" target="_blank" rel="noopener">github.com</a><br/> <b>awesome-pytest</b>: <a href="https://github.com/augustogoulart/awesome-pytest" target="_blank" rel="noopener">github.com</a><br/> <b>Tenacity</b>: <a href="https://tenacity.readthedocs.io/en/latest/" target="_blank" rel="noopener">readthedocs.io</a><br/> <b>Stamina</b>: <a href="https://github.com/hynek/stamina" target="_blank" rel="noopener">github.com</a><br/> <b>Flaky Test Management</b>: <a href="https://docs.cypress.io/guides/cloud/flaky-test-management" target="_blank" rel="noopener">docs.cypress.io</a><br/> <b>Flaky Test Management (Datadog)</b>: <a href="https://docs.datadoghq.com/continuous_integration/guides/flaky_test_management/" target="_blank" rel="noopener">datadoghq.com</a><br/> <b>Flaky Test Management (Spotify)</b>: <a href="https://engineering.atspotify.com/2019/11/test-flakiness-methods-for-identifying-and-dealing-with-flaky-tests/" target="_blank" rel="noopener">engineering.atspotify.com</a><br/> <b>Flaky Test Management (Google)</b>: <a href="https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html" target="_blank" rel="noopener">testing.googleblog.com</a><br/> <b>Detecting Test Pollution</b>: <a href="https://github.com/asottile/detect-test-pollution" target="_blank" rel="noopener">github.com</a><br/> <b>Surveying the developer experience of flaky tests paper</b>: <a href="https://www.gregorykapfhammer.com/research/papers/parry2022b/" target="_blank" rel="noopener">www.gregorykapfhammer.com</a><br/> <b>Build Kite CI/CD</b>: <a href="https://buildkite.com" target="_blank" rel="noopener">buildkite.com</a><br/> <b>Flake It: Finding and Fixing Flaky Test Cases</b>: <a href="https://github.com/flake-it" target="_blank" rel="noopener">github.com</a><br/> <b>Unflakable</b>: <a href="https://unflakable.com" target="_blank" rel="noopener">unflakable.com</a><br/> <b>CircleCI Test Detection</b>: <a href="https://circleci.com/blog/introducing-test-insights-with-flaky-test-detection/" target="_blank" rel="noopener">circleci.com</a><br/> <b>Watch this episode on YouTube</b>: <a href="https://www.youtube.com/watch?v=UIgj3gJpwS4" target="_blank" rel="noopener">youtube.com</a><br/> <br/> <b>--- Stay in touch with us ---</b><br/> <b>Subscribe to us on YouTube</b>: <a href="https://talkpython.fm/youtube" target="_blank" rel="noopener">youtube.com</a><br/> <b>Follow Talk Python on Mastodon</b>: <a href="https://fosstodon.org/web/@talkpython" target="_blank" rel="noopener"><i class="fa-brands fa-mastodon"></i>talkpython</a><br/> <b>Follow Michael on Mastodon</b>: <a href="https://fosstodon.org/web/@mkennedy" target="_blank" rel="noopener"><i class="fa-brands fa-mastodon"></i>mkennedy</a><br/></div><br/> <strong>Sponsors</strong><br/> <a href='https://talkpython.fm/done-with-pycharm'>PyCharm</a><br> <a href='https://talkpython.fm/sentry'>Sentry Error Monitoring, Code TALKPYTHON</a><br> <a href='https://talkpython.fm/training'>Talk Python Training</a>
Categories: FLOSS Project Planets

The Drop Times: A Chaiwala Tale to Break the Monotony

Planet Drupal - Mon, 2023-09-11 01:17

On my way home each evening, I stop for 'chai' (tea); even better, I stop to watch the chaiwala (tea barista) show off his swag. Amidst the crowd of onlookers, he effortlessly tosses spoonfuls of sugar into a cup, then adds tea and a dash of milk. But the true display of his expertise lies in the mixing part. The distance between the two cups used to mix the chai is directly proportional to the swag. It's a visual representation of his flair and confidence. The longer the pour, the higher the swag, and the more mesmerized the audience becomes.

But as I stand there, sipping my chai and reflecting on this daily spectacle, I can't help but draw parallels to life itself. Just as the chaiwala's captivating act can slip into mundanity when it becomes a routine, an individual's life can also fall prey to a monotonous existence when confined to a single trade or skill. It's a state of mere existence, as Oscar Wilde so eloquently put it.

"To live is the rarest thing in the world. Most people exist, that is all!"

Oscar Wilde, The Soul of Man Under Socialism.

This sentiment serves as a poignant reminder that life is not meant to be merely an existence but a journey filled with exploration and growth. The chaiwala's swag, while captivating, is ultimately an everyday performance. On the other hand, in the world of web development, Drupal enthusiasts embrace the mantra of growth that comes from exploration and collaboration. They understand that being stuck in one place can lead to a dull and repetitive existence. Therefore, the Drupal community not only hones their skills but also actively encourages others to join in. On that note, let me take you through the major inputs from last week.

The DropTimes have started a new initiative for a weekly feature that deals with Drupal modules that have thrived and stood the test of time. A curated list of 15 exceptional modules has already been unveiled, and we eagerly anticipate further contributions from enthusiastic members of the Drupal community. Southeast's biggest Drupal Conference, DrupalCamp Atlanta, was held on September 08, 2023, and we had the opportunity to sit down for a Zoom interview with the Lead Organizer, Kaleem Clarkson, who announced his farewell from the event after ten long years of organizing it.

On another exciting note, today, September 11, 2023, marks the end of regular registration of DrupalCon Lille 2023. Secure your seats before the end of the day to save a whopping €130. The 2023 edition of the Debian Conference, DebConf'23, was hosted in the land of spices, Kerala. EvolveDrupal Toronto had a magnificent conclusion with EvolveUX+ Mini-Conference, a dynamic conference within a conference.

The Drupal community is abuzz with excitement about the annual elections for the Drupal Association board; the voting opens on September 12, 2023. Globant's upcoming digital marketing and digital experience conference highlights a training session titled Drupal CMS: A Catalyst for AI on September 14, 2023. Design4Drupal Boston's September webinar focuses on web design accessibility and will be conducted on September 20, 2023.

In recent developments, Genero launched the "Kamihaya" distribution for Drupal. Also, Debug Academy is gearing up to launch an immersive Drupal 9 and 10 Developer course, set to kick off on September 24 and run until September 27, 2023. ImageX Media shared insights on the progress of Drupal 10 to 11 and what to expect in the future in the latest blog post. Acquia shared essential Drupal website maintenance tips, and Philip Norton in Hashbangcode published a guide to third-party settings in Drupal.

Revanth Technology is now offering Drupal Online Training in Hyderabad, India. Amazee.io is hosting a webinar on September 21, 2023, titled "The Future of the Open Web is Composable." The Drupal Academy tutorial explores the potential of services in both Drupal 9 and Drupal 10. The Aveiro 2023 Free Software Festival is scheduled to run from September 15 to 17, 2023.

That's all for the week.

Yours sincerely,     
Alka Elizabeth     
Sub Editor, The DropTimes

Categories: FLOSS Project Planets

Debian Brasil: Debian Day 30 anos in Maceió - Brazil

Planet Debian - Mon, 2023-09-11 01:00

The Debian Day in Maceió 2023 took place at the Senai auditorium in Maceió with the support and organization of Oxe Hacker Club.

There were around 90 people registered, and 40 ateendees present on Saturday to participate in the event, which featured the following 6 talks:

  • Debian Package - Daniel Pimentel
  • Attacking Linux EDRs for Fun and Profit - Tiago Peixoto
  • Docker: Introdução ao mundo dos containers - Baltazar
  • Hardening, Debian e CIS Benchmarks - Moises
  • Carreira e Software Livre em Cyber Security - Edo
  • O Software Livre já pode pagar minhas contas? - Gilberto Martins

Debian Day also had an install fest and unconference (random chat, food and drinks).

Categories: FLOSS Project Planets

Debian Brasil: Debian Day 30 anos em Maceió

Planet Debian - Mon, 2023-09-11 01:00

O Debian Day em Maceió 2023 foi realizado no auditório do Senai em Maceió com apoio e realização do Oxe Hacker Club.

Se inscreveram cerca de 90 pessoas, e 40 estiveram presentes no sábado para participarem do evento que contou com as 6 palestras a seguir:

  • Debian Package - Daniel Pimentel
  • Attacking Linux EDRs for Fun and Profit - Tiago Peixoto
  • Docker: Introdução ao mundo dos containers - Baltazar
  • Hardening, Debian e CIS Benchmarks - Moises
  • Carreira e Software Livre em Cyber Security - Edo
  • O Software Livre já pode pagar minhas contas? - Gilberto Martins

O Debian Day teve ainda um install fest e desconferência (papo aleatório, comes e bebes).

Categories: FLOSS Project Planets

Dirk Eddelbuettel: RcppArmadillo 0.12.6.4.0 on CRAN: Another Upstream Bugfix

Planet Debian - Sun, 2023-09-10 20:30

Armadillo is a powerful and expressive C++ template library for linear algebra and scientific computing. It aims towards a good balance between speed and ease of use, has a syntax deliberately close to Matlab, and is useful for algorithm development directly in C++, or quick conversion of research code into production environments. RcppArmadillo integrates this library with the R environment and language–and is widely used by (currently) 1096 other packages on CRAN, downloaded 30.5 million times (per the partial logs from the cloud mirrors of CRAN), and the CSDA paper (preprint / vignette) by Conrad and myself has been cited 552 times according to Google Scholar.

This release brings bugfix upstream release 12.6.4. Conrad prepared this a few days ago; it takes me the usual day or so to run reverse-dependency check against the by-now almost 1100 CRAN packages using RcppArmadillo. And this time, CRAN thought it had found two issues when I submitted and it took two more days til we were all clear about those two being false positives (as can, and does, happen). So today it reached CRAN.

The set of changes follows.

Changes in RcppArmadillo version 0.12.6.4.0 (2023-09-06)
  • Upgraded to Armadillo release 12.6.4 (Cortisol Retox)

    • Workarounds for bugs in Apple accelerate framework

    • Fix incorrect calculation of rcond for band matrices in solve()

    • Remove expensive and seldom used optimisations, leading to faster compilation times

Courtesy of my CRANberries, there is a diffstat report relative to previous release. More detailed information is on the RcppArmadillo page. Questions, comments etc should go to the rcpp-devel mailing list off the Rcpp R-Forge page.

If you like this or other open-source work I do, you can sponsor me at GitHub.

This post by Dirk Eddelbuettel originated on his Thinking inside the box blog. Please report excessive re-aggregation in third-party for-profit settings.

Categories: FLOSS Project Planets

Stack Abuse: Parsing Boolean Values with Argparse in Python

Planet Python - Sun, 2023-09-10 18:29
Introduction

In this Byte, we'll be looking into Python's argparse module and how we can use it to parse boolean values from the command line. This is often used when you're writing a command line tool or even a more complex application. Understanding argparse and its functionalities can make your life a lot easier when taking input from the command line.

The Argparse Module

Argparse is a Python module that makes it easy to write user-friendly command-line interfaces. The argparse module can handle positional arguments, optional arguments, and even sub-commands. It can also generate usage and help messages, and throw errors when users give the program invalid arguments.

Argparse has been part of the Python standard library since version 2.7, so you don't need to install anything extra to start using it. It's designed to replace the older optparse module, and offers a more flexible interface.

Basic Usage of Argparse

To start using argparse, you first need to import it:

import argparse

Next, you create a parser object:

parser = argparse.ArgumentParser(description='My first argparse program.')

The ArgumentParser object holds all the information necessary to parse the command line into Python data types. The description argument to ArgumentParser is a text to display before the argument help (the --help text).

To add arguments to your program, you use the add_argument() method:

parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')

Finally, you can parse the command-line arguments with parse_args():

args = parser.parse_args() print(args.accumulate(args.integers))

This will parse the command line, convert each argument to the appropriate type, and then invoke any actions you've specified.

Parsing Boolean Values

Now, let's see how we can parse boolean values with argparse. For this, we'll use the built-in store_true or store_false actions. These actions store the values True and False respectively.

import argparse parser = argparse.ArgumentParser(description='Parse boolean values.') parser.add_argument('--flag', dest='flag', action='store_true', help='Set the flag value to True.') parser.add_argument('--no-flag', dest='flag', action='store_false', help='Set the flag value to False.') parser.set_defaults(flag=True) args = parser.parse_args() print('Flag:', args.flag)

In this script, we've set up two command-line options: --flag and --no-flag. The --flag option sets args.flag to True, and the --no-flag option sets it to False. If neither option is given, the set_defaults() method sets args.flag to True.

Here's how it works in the command line:

$ python bool_argparse.py --flag Flag: True $ python bool_argparse.py --no-flag Flag: False $ python bool_argparse.py Flag: True

As you can see, argparse makes it easy to parse boolean values, and even to set default values. This can be very useful in a lot of applications, from simple scripts to more complex command-line interfaces.

Other Ways to Pass Boolean Values via CLI

In addition to the store_true and store_false actions, there are other ways you can pass boolean values using the command line interface. One common alternative is to pass the boolean value as a string, and then convert this string to a boolean in your script.

Let's consider the following example:

import argparse def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser() parser.add_argument('--flag', type=str2bool, help='Boolean flag') args = parser.parse_args() print(args.flag)

Here we've define a helper function str2bool that converts a string to a boolean value. It works by checking for common "truthy" and "falsey" values.

We then use this function as the type for our argument. This allows us to pass boolean values as strings, like this:

$ python script.py --flag yes True $ python script.py --flag no False Conclusion

In this Byte, we've shown some examples on how to parse boolean values with the argparse module in Python. We've looked at the basic usage of argparse, how to parse boolean values, and some alternatives for handling boolean values. Whether you're writing a simple script for personal use or a complex application to be used by others, argparse is a useful tool to make your script more flexible and user-friendly.

Categories: FLOSS Project Planets

Jelmer Vernooij: Transcontinental Race No 9

Planet Debian - Sun, 2023-09-10 16:00

After cycling the Northcape 4000 (from Italy to northern Norway) last year, I signed up for the transcontinental race this year.

The Transcontinental is bikepacking race across Europe, self-routed (but with some mandatory checkpoints), unsupported and with a distance of usually somewhere around 4000 km. The cut-off time is 15 days, with the winner usually taking 7-10 days.

This year, the route went from Belgium to Thessaloniki in Greece, with control points in northern Italy, Slovenia, Albania and Meteora (Greece).

The event was great - it was well organised and communication was a lot better than at the Northcape. It did feel very different from the Northcape, though, being a proper race. Participants are not allowed to draft off each other or help each other, though a quick chat here or there as you pass people is possible, or when you’re both stopped at a shop or control point.

My experience

The route was beautiful - the first bit through France was a bit monotonic, but especially the views in the alps were amazing. Like with other long events, the first day or two can be hard but once you get into the rhythm of things it’s a lot easier.

From early on, I lost a lot of time. We started in the rain, and I ran several flats in a row, just 4 hours in. In addition to that, the thread on my pump had worn so it wouldn’t fit on some of my spare tubes, and my tubes were all TPU - which are hard to patch. So at 3 AM I found myself by the side of an N-road in France without any usable tubes to put in my rear wheel. I ended up walking 20km to the nearest town with a bike shop, where they fortunately had good old butyl tubes and a working pump. But overall, this cost me about 12 hours in total.

In addition to that, my time management wasn’t great. On previous rides, I’d usually gotten about 8 hours of sleep per night while staying in hotels. On the transcontinental I had meant to get less sleep but still stay in hotels most night, but I found that not all hotels accomodated well for that - especially with a bike. So I ended up getting more sleep than I had intended, and spending more time off the bike than I had planned - close to 11 or 12 hours per day. I hadn’t scheduled much time off work after the finish either, so arriving in Greece late wasn’t really an option.

And then, on an early morning in Croatia (about 2000km in) in heavy fog, I rode into a kerb at 35 km/h, bending the rim of my front wheel (but fortunately not coming off my bike). While I probably would have been able to continue with a replacement wheel (and mailing the broken one home), that would have taken another day to sort out and I almost certainly wouldn’t have been able to source a new dynamo wheel in Croatia - which would have made night time riding a lot harder. So I decided to scratch and take the train home from Zagreb.

Overall, I really enjoyed the event and I think I’ve learned some useful lessons. I’ll probably try again next year.

Categories: FLOSS Project Planets

Pages