Python

# Events - 14 October - CLEpy meetup - via https://fosstodon.org/@clepy/113311328924148486 # Releases - 14 October - `pyparsing` 3.2.0 - via https://fosstodon.org/@ptmcg/113302603878074247 - 15 October - `eve` 2.2 - via https://fosstodon.org/@nicola/113310333550705121 - `pillow` 11.0.0 - via https://mastodon.social/@hugovk/113312137194438039 (and https://fosstodon.org/@pillow/113312110767354794) - `validate-pyproject` 0.21 - via https://fosstodon.org/@henryiii/113312246938821428

17
1
bitscomplicated.com

I am including the full text of the post --- Despite not being a pure functional language, a lot of praise that python receives are for features that stem from functional paradigms. Many are second nature to python programmers, but over the years I have seen people miss out on some important features. I gathered a few, along with examples, to give a brief demonstration of the convenience they can bring. ## Replace `if/else` with `or` With values that might be `None`, you can use `or` instead of `if/else` to provide a default. I had used this for years with Javascript, without knowing it was also possible in Python. ```python def get_greeting_prefix(user_title: str | None): if user_title: return user_title return "" ``` Above snippet can shortened to this: ```python def get_greeting_prefix(user_title: str | None): return user_title or "" ``` ## Pattern Matching and Unpacking The overdue arrival of `match` to python means that so many `switch` style statements are expressed instead with convoluted `if/else` blocks. Using `match` is not even from the functional paradigm, but combining it with unpacking opens up new possibilities for writing more concise code. Let's start by looking at a primitive example of unpacking. Some libraries have popularised use of `[a, b] = some_fun()`, but unpacking in python is much powerful than that. ```python [first, *mid, last] = [1, 2, 3, 4, 5] # first -> 1, mid -> [2, 3, 4], last -> 5 ``` ### Matching Lists Just look at the boost in readability when we are able to name and extract relevant values effortlessly: ``` python def sum(numbers: [int]): if len(numbers) == 0: return 0 else: return numbers[0] + sum(numbers[1:]) ``` ```python def sum(numbers: [int]): match numbers: case []: return 0 case [first, *rest]: return first + sum(rest) ``` ### Matching Dictionaries Smooth, right? We can go even further with dictionaries. This example is not necessarily better than its `if/else` counterpart, but I will use it for the purpose of demonstrating the functionality. ```python sample_country = {"economic_zone": "EEA", "country_code": "AT"} def determine_tourist_visa_requirement(country: dict[str, str]): match country: case {"economic_zone": "EEA"}: return "no_visa" case {"country_code": code} if code in tourist_visa_free_countries: return "non_tourist_visa_only" case default: return "visa_required" ``` ### Matching `Dataclasses` Let’s write a function that does a primitive calculation of an estimated number of days for shipment ```python @dataclass class Address: street: str zip_code: str country_code: str ``` ```python def calculate_shipping_estimate(address: Address) -> int: match address: case Address(zip_code=zc) if close_to_warehouse(zc): return 1 case Address(country_code=cc) if cc in express_shipping_countries: return 2 case default: return provider_estimate(city.coordinates) ``` ## Comprehensions List comprehensions get their deserved spotlight, but I’ve seen cases where dictionary comprehension would’ve cut multiple lines. You can look at examples [on this page on python.org](https://peps.python.org/pep-0274/#examples)

24
0

I am working on a rudimentary Breakout clone, and I was doing the wall collision. I have a function that I initially treated as a Boolean, but I changed it to return a different value depending on which wall the ball hit. I used the walrus operator to capture this value while still treating the function like a bool. I probably could have just defined a variable as the function's return value, then used it in an if statement. But it felt good to use this new thing I'd only heard about, and didn't really understand what it did. I was honestly kind of surprised when it actually worked like I was expecting it to! Pretty cool.

45
2

(For context, I'm basically referring to Python 3.12 "multiprocessing.Pool Vs. concurrent.futures.ThreadPoolExecutor"...) Today I read that multiple cores (parallelism) help in CPU bound operations. Meanwhile, multiple threads (concurrency) is due when the tasks are I/O bound. Is this correct? Anyone cares to elaborate for me? At least from a theorethical standpoint. Of course, many real work has a mix of both, and I'd better start with profiling where the bottlenecks really are. If serves of anything having a concrete "algorithm". Let's say, I have a function that applies a map-reduce strategy reading data chunks from a file on disk, and I'm computing some averages from these data, and saving to a new file.

16
15
https://quentin.pradet.me/blog/migrating-a-python-library-to-uv.html

Via https://fosstodon.org/@quentinpradet/113311962538364238

8
0

Hi, I'm already using ```python from smtplib import SMTP_SSL from email.message import EmailMessage ``` To send emails. Now I would like to be able to encrypt them with the public key of the recipient. ( `PublicKey.asc` ) ::: spoiler an A.I provide me this ```python import smtplib from email.message import EmailMessage from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.ciphers.aead import AESGCM # Load the ECC public key from the .asc file with open('recipient_public_key.asc', 'rb') as key_file: public_key_bytes = key_file.read() public_key = ec.EllipticCurvePublicKey.from_public_bytes( ec.SECP384R1(), public_key_bytes ) # Create the email message msg = EmailMessage() msg.set_content('This is the encrypted email.') msg['Subject'] = 'Encrypted Email' msg['From'] = 'you@example.com' msg['To'] = 'recipient@example.com' # Encrypt the email message using the ECC public key nonce = bytes.fromhex('000102030405060708090a0b0c0d0e0f') cipher = AESGCM(public_key.public_key().secret_key_bytes) ciphertext = cipher.encrypt(nonce, msg.as_bytes(), None) # Send the encrypted email server = smtplib.SMTP('smtp.example.com') server.send_message(msg, from_addr='you@example.com', to_addr='recipient@example.com') server.quit() # Save the encrypted email to a file with open('encrypted_email.bin', 'wb') as f: f.write(ciphertext) ``` ::: I like the approach, only one "low level" import [cryptography](https://pypi.org/project/cryptography/) but the code seem wrong. if the body has been encrypted as `ciphertext` I don't see this one included while sending the email. How are you doing it ? or do you have good tutorial, documentations ? because I found nothing "pure and simple" meaning not with of unnecessary stuff. Thanks.

11
6
blog.miguelgrinberg.com

via https://mstdn.social/@miguelgrinberg/113266572735273155

34
2

I am trying to follow this tutorial ([Announcing py2wasm: A Python to Wasm compiler · Blog · Wasmer](https://wasmer.io/posts/py2wasm-a-python-to-wasm-compiler)) and run py2wasm but I am getting this weird problem. First is that I believe py2wasm might be just an executable like other pip packages I install, or a bat file. (I am fairly new to python and I just want to convert a python code to wasm). But when I head over to `C:\Users\USER\AppData\Local\Programs\Python\Python312\Scripts` where the pip packages are located, I can't seem to find any file related to py2wasm. Running `dir C:\Users\USER\AppData\Local\Programs\Python\Python312\Lib\site-packages\py2wasm*` to check any related files about the py2wasm folder only leads to this ```powershell Directory: C:\Users\USER\AppData\Local\Programs\Python\Python312\Lib\site-packages Mode LastWriteTime Length Name --- d----- 04-10-2024 19:54 py2wasm-2.6.2.dist-info ``` Also, before you could ask yeah I could run other pip packages such as yt-dlp.

7
3
www.youtube.com

via https://fosstodon.org/@europython/113242551122295216

12
1
www.pythonmorsels.com

via https://mastodon.social/@treyhunner/113230504133387015

19
0
https://www.youtube.com/watch?v=8UuW8o4bHbw

via https://mastodon.social/@hynek/113227146595211210

35
44
danielquinn.org

I've been writing code professionally for 24 years, 15 of which has been Python and 9 years of that with Docker. I got tired of running into the same complications every time I started a new job, so I wrote this. Maybe you'll find it useful, or it could even start a conversation, but this post has been a long time coming. **Update**: I had a few requests for a demo repo as a companion to this post, [so I wrote one today](https://danielquinn.org/blog/developing-with-docker/). It includes a very small Django demo user Docker, Compose, and GitLab CI.

62
19
github.com

A library for creating fully typed and declarative API clients, quickly and easily. **What would an API client with this library look like?** For a single API endpoint over HTTP GET, it could look something like this: ``` from dataclasses import dataclass import quickapi # An example type that will be part of the API response @dataclass class Fact: fact: str length: int # What the API response should look like @dataclass class ResponseBody: current_page: int data: list[Fact] # Now we can define our API class MyApi(quickapi.BaseApi[ResponseBody]): url = "https://catfact.ninja/facts" response_body = ResponseBody ``` And you would use it like this: ``` response = MyApi().execute() # That's it! Now `response` is fully typed (including IDE support) and conforms to our `ResponseBody` definition assert isinstance(response.body, ResponseBody) assert isinstance(response.body.data[0], Fact) ``` It also supports `attrs` or `pydantic` (or `dataclasses` as above) for your model/type definitions, including validation and types/data conversion. I have a lot more examples (e.g. POST requests, query string params, authentication, error handling, model validation and conversion, multiple API endpoints) on the repo's README. I've shared this one here before but it's been a while and I've added a lot of features since. Github repo: https://github.com/martinn/quickapiclient

24
0
adamj.eu

via https://fosstodon.org/@adamchainz/113158552844057284

16
0
www.pythonmorsels.com

via https://mastodon.social/@treyhunner/113150024938712511

45
0
https://simonwillison.net/2024/Sep/8/uv-under-discussion-on-mastodon/

via https://fedi.simonwillison.net/@simon/113102865356065670

34
15

New to CircuitPython, this feels like it should work according to the docs but it prints six `False`s. Any ideas? ``` #!/usr/bin/env python import board import digitalio import time class body_controller: def __init__(self): SWDIO = board.D5 self._reset_pin = digitalio.DigitalInOut(SWDIO) print(self._reset_pin.value) self._reset_pin.switch_to_output(True) print(self._reset_pin.value) def turn_on(self): print(self._reset_pin.value) self._reset_pin.value = False print(self._reset_pin.value) time.sleep(1) print(self._reset_pin.value) self._reset_pin.value = True print(self._reset_pin.value) body = body_controller() time.sleep(1) body.turn_on() time.sleep(1) ```

11
1
discuss.python.org

via https://mastodon.social/@hugovk/113097578994494173

20
6

Ive learned a decent bit of python from a trade school I was in and I am really interested in learning more and eventually do freelance work And I'm looking for advice on ensuring I know enough to do that as well as some advice getting started

18
5
https://www.trickster.dev/post/lesser-known-parts-of-python-standard-library/

> In this article we will explore some lesser known, but interesting and useful corners of Python standard library. ... > To provide more powerful containers for storing data in memory Python ships a `collection` module ... > Python has `with` keyword to create context manager that will auto-cleanup things within lexical scope ... > To address this problem, Python ships `decimal` module that allows us represent decimal numbers as Python objects with operator overloading ... > Likewise, we can run into problem when dealing with fractions - one third is not exactly equal to 0.333… Python ships with `fractions` module to represent them as Python objects with operator overloading ... > The standard Python installation ships with `dis` module that takes Python code units (e.g. a function) and disassembles the code into a kind of pseudo-assembler ... > Python `statistics` module provides a small toolkit of statistical algorithms for relatively simple applications where it is an overkill to use Pandas or Numpy: standard deviation, several kinds of average of numeric data, linear regression, correlation, normal distribution and others ... > To make this easier Python ships a `webbrowser` module with simple API to make a browser show a page ... > To make this less terrible Python ships `zipapp` module with CLI tool and Python API to package Python code into single file packages ...

29
0

Hi, folks! I'd like to set up my emacs with `lsp-mode` and `lsp-ui`, but I am finding myself in some analysis paralysis. Ruling out the Palantir language server because it's deprecated and because it's Palantir, that still leaves me with *five* [language server recommendations from `lsp-mode`](https://emacs-lsp.github.io/lsp-mode/page/languages/). Anybody have any opinions they'd like to share? Any really bad experiences I should avoid? How do I configure your favorite? (Feel free to assume I know very little about configuring emacs.) If it makes a difference, I am a [poetry](https://python-poetry.org/) user and a religious `mypy --strict` user. Thanks in advance!

16
10
https://youtu.be/wgkC8SxraAQ?si=8Mf45sBKo4BR-qX5&t=315

I'm currently doing Dr. Charles Severence's lessons on FreeCodeCamp to try to learn Python3. I'm on lesson exercise 02_03 and confused about multiplying floating-point and integer values. The goal is to write a Python program multiplying hours worked by pay rate to come up with a pay quantity. This is the code I wrote: h = input("Enter hours: ") r = input("Enter pay rate: ") p = float(h) * r I got a traceback error, and the video said the correct way to solve said error was change Line 3 from `p = float(h) * r` to `p = float(h) * float(r)`. However, what I'm confused about is why would I need to change `r` to a floating-point value when it's *already* a floating-point value (since it'd be a currency value like 5.00 or something once I typed it in per the `input()` command*? What am I missing here?   --- *I can't remember: are the individual commands in a python line called "commands"?     --- **Edit**: Wrote plus signs in my post here instead of asterisks. Fixed.   --- **EDIT**: Thanks to [@Labna@lemmy.world](https://lemmy.world/u/Labna) and [@woop_woop@lemmy.world](https://lemmy.world/u/woop_woop). I thought that the `input()` function was a string until the end-user types something in upon being prompted, and then becomes a floating-point value or integer value (or stays a string) according to what was typed. This is incorrect: the value is a string regardless of what is typed unless it is then converted to another type.

7
14

I read some articles about using a virtual environment in Docker. Their argument are that the purpose of virtualization in Docker is to introduce isolation and limit conflicts with system packages etc. However, aren't Docker and Python-based images (e.g., python:*) already doing the same thing? Can someone eli5 this whole thing?

25
20
hynek.me

via https://mastodon.social/@hynek/113067230489781151

44
10
blog.codingconfessions.com

> For every bytecode compiled language, the most interesting part of its implementation is its virtual machine (also referred to as the bytecode interpreter) where the bytecode execution takes place. Because this is such a crucial part of the language machinery, its implementation has to be highly performant. Even if you are not a compiler engineer, learning about such internal implementation can give you new performance tricks and insights that you may be able to use in other places of your job. And, if you are a compiler engineer then you should always look around how other languages are implemented to pickup implementation details that you may not be aware of. > In this article, we are going to be discussing the bytecode instruction format of CPython, followed by the implementation of the bytecode evaluation loop of the interpreter where the bytecode execution takes place.

25
1
discuss.python.org

Original comment: > I don’t know much about voting systems, but I know someone who does. Unfortunately he’s currently banned. Maybe we can wait until his 3-month ban expires and ask him for advice? [Previous discussion](https://programming.dev/post/18074128)

73
33
https://lwn.net/Articles/983870/

> CircuitPython is an open-source implementation of the Python programming language for microcontroller boards. The project, which is sponsored by Adafruit Industries, is designed with new programmers in mind, but it also has many features that may be of interest to more-experienced developers. The recent 9.1.0 release adds a few minor features, but it follows just a few months after CircuitPython 9.0.0, which brings some more significant changes, including improved graphics and USB support. > CircuitPython is a fork of MicroPython (previously covered on LWN) with several changes designed to make the language easier for beginners to use. CircuitPython has a universal hardware API and is more compatible with the CPython standard library, for example. CircuitPython has some limitations compared to MicroPython, particularly with respect to concurrency, but is otherwise just as powerful. ... > This difference in APIs make sense when looking at the main goals of each project. MicroPython describes the language as ""a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments"". In contrast, Adafruit's "What is CircuitPython?" page says: ""CircuitPython is a programming language designed to simplify experimenting and learning to program on low-cost microcontroller boards."" Adafruit recommends CircuitPython for users who ""want to get up and running quickly"" or ""are new to programming"". > CircuitPython supports most of the core language features of CPython, although some features are missing due to the limited resources found on microcontroller boards compared to the much more powerful computers on which CPython typically runs. Many of those missing features will be the same as those on a comparison between CPython and MicroPython reports. In addition, as CircuitPython's main README explains: ""Modules with a CPython counterpart, such as time, os and random, are strict subsets of their CPython version. Therefore, code from CircuitPython is runnable on CPython but not necessarily the reverse.""

17
1
www.mattlayman.com

Via https://mastodon.social/@mblayman/113028791455699212

26
1