Quantcast
Channel: Planet Python
Viewing all 23442 articles
Browse latest View live

Trey Hunner: Switching from virtualenvwrapper to direnv, Starship, and uv

$
0
0

Earlier this week I considered whether I should finally switch away from virtualenvwrapper to using local .venv managed by direnv.

I’ve never seriously used direnv, but I’ve been hearing Jeff and Hynek talk about their use of direnv for a while.

After a few days, I’ve finally stumbled into a setup that works great for me. I’d like to note the basics of this setup as well as some fancy additions that are specific to my own use case.

My old virtualenvwrapper workflow

First, I’d like to note my old workflow that I’m trying to roughly recreate:

  1. I type mkvenv3 <project_name> to create a new virtual environment for the current project directory and activate it
  2. I type workon <project_name> when I want to workon that project: this activates the correct virtual environment and changes to the project directory

The initial setup I thought of allows me to:

  1. Run echo layout python > .envrc && direnv allow to create a virtual environment for the current project and activate it
  2. Change directories into the project directory to automatically activate the virtual environment

The more complex setup I eventually settled on allows me to:

  1. Run venv <project_name> to create a virtual environment for the current project and activate it
  2. Run workon <project_name> to change directories into the project (which automatically activates the virtual environment)

The initial setup

First, I installed direnv and added this to my ~/.zshrc file:

1
eval"$(direnv hook zsh)"

Then whenever I wanted to create a virtual environment for a new project I created a .envrc file in that directory, which looked like this:

1
layout python

Then I ran direnv allow to allow, as direnv instructed me to, to allow the new virtual environment to be automatically created and activated.

That’s pretty much it.

Unfortunately, I did not like this initial setup.

No shell prompt?

The first problem was that the virtual environment’s prompt didn’t show up in my shell prompt. This is due to a direnv not allowing modification of the PS1 shell prompt. That means I’d need to modify my shell configuration to show the correct virtual environment name myself.

So I added this to my ~/.zshrc file to show the virtual environment name at the beginning of my prompt:

1234567
# Add direnv-activated venv to promptshow_virtual_env(){if[[ -n "$VIRTUAL_ENV_PROMPT"&& -n "$DIRENV_DIR"]];thenecho"($(basename $VIRTUAL_ENV_PROMPT)) "fi}PS1='$(show_virtual_env)'$PS1

Wrong virtual environment directory

The next problem was that the virtual environment was placed in .direnv/python3.12. I wanted each virtual environment to be in a .venv directory instead.

To do that, I made a .config/direnv/direnvrc file that customized the python layout:

1234567891011121314
layout_python(){if[[ -d ".venv"]];thenVIRTUAL_ENV="$(pwd)/.venv"fiif[[ -z $VIRTUAL_ENV|| ! -d $VIRTUAL_ENV]];then        log_status "No virtual environment exists. Executing \`python -m venv .venv\`."        python -m venv .venv
VIRTUAL_ENV="$(pwd)/.venv"fi# Activate the virtual environment    . $VIRTUAL_ENV/bin/activate
}

Loading, unloading, loading, unloading…

I also didn’t like the loading and unloading messages that showed up each time I changed directories. I removed those by clearing the DIRENV_LOG_FORMAT variable in my ~/.zshrc configuration:

1
export DIRENV_LOG_FORMAT=

The more advanced setup

I don’t like it when all my virtual environment prompts show up as .venv. I want ever prompt to be the name of the actual project… which is usually the directory name.

I also really wanted to be able to type venv to create a new virtual environment, activate it, and create the .envrc file for my automatically.

Additionally, I thought it would be really handy if I could type workon <project_name> to change directories to a specific project.

I made two aliases in my ~/.zshrc configuration for all of this:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
venv(){local venv_name=${1:-$(basename "$PWD")}local projects_file="$HOME/.projects"# Check if .envrc already existsif[ -f .envrc ];thenecho"Error: .envrc already exists">&2
return 1
fi# Create venvif ! python3 -m venv --prompt "$venv_name";thenecho"Error: Failed to create venv">&2
return 1
fi# Create .envrcecho"layout python"> .envrc
# Append project name and directory to projects fileecho"${venv_name} = ${PWD}">> $projects_file# Allow direnv to immediately activate the virtual environment    direnv allow
}workon(){local project_name="$1"local projects_file="$HOME/.projects"local project_dir
# Check for projects config fileif[[ ! -f "$projects_file"]];thenecho"Error: $projects_file not found">&2
return 1
fi# Get the project directory for the given project nameproject_dir=$(grep -E "^$project_name\s*=""$projects_file"| sed 's/^[^=]*=\s*//')# Ensure a project directory was foundif[[ -z "$project_dir"]];thenecho"Error: Project '$project_name' not found in $projects_file">&2
return 1
fi# Ensure the project directory existsif[[ ! -d "$project_dir"]];thenecho"Error: Directory $project_dir does not exist">&2
return 1
fi# Change directoriescd"$project_dir"}

Now I can type this to create a .venv virtual environment in my current directory, which has a prompt named after the current directory, activate it, and create a .envrc file which will automatically activate that virtual environment (thanks to that ~/.config/direnv/direnvrc file) whenever I change into that directory:

1
$ venv

If I wanted to customized the prompt name for the virtual environment, I could do this:

1
$ venv my_project

When I wanted to start working on that project later, I can either change into that directory or if I’m feeling lazy I can simply type:

1
$ workon my_project

That reads from my ~/.projects file to look up the project directory to switch to.

Switching to uv

I also decided to try using uv for all of this, since it’s faster at creating virtual environments. One benefit of uv is that it tries to select the correct Python version for the project, if it sees a version noted in a pyproject.toml file.

Another benefit of using uv, is that I should also be able to update the venv to use a specific version of Python with something like --python 3.12.

Here are the updated shell aliases for the ~/.zshrc for uv:

123456789101112131415161718192021222324252627282930313233
venv(){local venv_name
local dir_name=$(basename "$PWD")# If there are no arguments or the last argument starts with a dash, use dir_nameif[$# -eq 0]||[["${!#}"== -* ]];thenvenv_name="$dir_name"elsevenv_name="${!#}"set -- "${@:1:$#-1}"fi# Check if .envrc already existsif[ -f .envrc ];thenecho"Error: .envrc already exists">&2
return 1
fi# Create venv using uv with all passed argumentsif ! uv venv --seed --prompt "$@""$venv_name";thenecho"Error: Failed to create venv">&2
return 1
fi# Create .envrcecho"layout python"> .envrc
# Append to ~/.projectsecho"${venv_name} = ${PWD}">> ~/.projects
# Allow direnv to immediately activate the virtual environment    direnv allow
}

Switching to starship

I also decided to try out using Starship to customize my shell this week.

I added this to my ~/.zshrc:

1
eval"$(starship init zsh)"

And removed this, which is no longer needed since Starship will be managing the shell for me:

1234567
# Add direnv-activated venv to promptshow_virtual_env(){if[[ -n "$VIRTUAL_ENV_PROMPT"&& -n "$DIRENV_DIR"]];thenecho"($(basename $VIRTUAL_ENV_PROMPT)) "fi}PS1='$(show_virtual_env)'$PS1

I also switched my python layout for direnv to just set the $VIRTUAL_ENV variable and add the $VIRTUAL_ENV/bin directory to my PATH, since the $VIRTUAL_ENV_PROMPT variable isn’t needed for Starship to pick up the prompt:

12345
layout_python(){VIRTUAL_ENV="$(pwd)/.venv"    PATH_add "$VIRTUAL_ENV/bin"export VIRTUAL_ENV
}

I also made a very boring Starship configuration in ~/.config/starship.toml:

123456789101112131415161718192021222324252627282930
format="""$python\$directory\$git_branch\$git_state\$character"""add_newline=false[python]format='([(\($virtualenv\))]($style))'style="bright-black"[directory]style="bright-blue"[character]success_symbol="[\\$](black)"error_symbol="[\\$](bright-red)"vimcmd_symbol="[❮](green)"[git_branch]format="[$symbol$branch]($style) "style="bright-purple"[git_state]format='\([$state($progress_current/$progress_total)]($style)\)'style="purple"[cmd_duration.disabled]

I setup such a boring configuration because when I’m teaching, I don’t want my students to be confused or distracted by a prompt that has considerably more information in it than their default prompt may have.

The biggest downside of switching to Starship has been my own earworm-oriented brain. As I update my Starship configuration files, I’ve repeatedly heard David Bowie singing “I’m a Starmaaan”. 🎶

Ground control to major TOML

After all of that, I realized that I could additionally use different Starship configurations for different directories by putting a STARSHIP_CONFIG variable in specific layouts. After that realization, I made my configuration even more vanilla and made some alternative configurations in my ~/.config/direnv/direnvrc file:

123456789101112
layout_python(){VIRTUAL_ENV="$(pwd)/.venv"    PATH_add "$VIRTUAL_ENV/bin"export VIRTUAL_ENV
export STARSHIP_CONFIG=/home/trey/.config/starship/python.toml
}layout_git(){export STARSHIP_CONFIG=/home/trey/.config/starship/git.toml
}

Those other two configuration files are fancier, as I have no concern about them distracting my students since I’ll never be within those directories while teaching.

You can find those files in my dotfiles repository.

The necessary tools

So I replaced virtualenvwrapper with direnv, uv, and Starship. Though direnv was is doing most of the important work here. The use of uv and Starship were just bonuses.

I am also hoping to eventually replace my pipx use with uv and once uv supports adding python3.x commands to my PATH, I may replace my use of pyenv with uv as well.

Thanks to all who participated in my Mastodon thread as I fumbled through discovering this setup.


Seth Michael Larson: EuroPython 2024 talks about security

$
0
0
EuroPython 2024 talks about security

EuroPython 2024 talks about security

Published 2024-10-04 by Seth Larson
Reading time: minutes

EuroPython 2024 which occurred back in July 2024 has published the talk recordings to YouTube earlier this week. I've been under the weather for most of this week, but have had a chance to listen to a few of the security-related talks in-between resting.

Counting down for Cyber Resilience Act: Updates and expectations

This talk was delivered by Python Software Foundation Executive Director Deb Nicholson and and Board Member Cheuk Ting Ho. The Cyber Resilience Act (CRA) is coming, and it'll affect more software than just the software written in the EU. Deb and Cheuk describe the recent developments in the CRA like the creation of a new entity called the "Open Source Steward" and how open source foundations and maintainers are preparing for the CRA.

For the rest of this year and next year I am focusing on getting the Python ecosystem ready for software security regulations like the CRA and SSDF from the United States.

Starting with improving the Software Bill-of-Materials (SBOM) story for Python, because this is required by both (and likely, future) regulations. Knowing what software you are running is an important first step towards being able to secure that same software.

To collaborate with other open source foundations and projects on this work, I've joined the Open Regulatory Compliance Working Group hosted by the Eclipse Foundation.

Towards licensing standardization in Python packaging

This talk was given by Karolina Surma and it detailed all the work that goes into researching, writing, and having a Python packaging standard accepted (spoiler: it's a lot!). Karolina is working on PEP 639 which is for adopting the SPDX licensing expression and identifier standards in Python as they are the current state of the art for modeling complex licensing situations accurately for machine (and human) consumption.

This work is very important for Software Bill-of-Materials, as they require accurate license information in this exact format. Thanks to Karolina, C.A.M. Gerlach, and many others for working for years on this PEP, it will be useful to so many uers once adopted!

The Update Framework (TUF) joins PyPI

This talk was given by Kairo de Araujo and Lukas Pühringer and it detailed the history and current status of The Update Framework (TUF) integration into the Python Package Index.

TUF provides better integrity guarantees for software repositories like PyPI like making it more difficult to "compel" the index to serve the incorrect artifacts and to make a compromise of PyPI easier to roll-back and be certain that files hadn't been modified. For a full history and latest status, you can view PEP 458 and the top-level GitHub issue for Warehouse.

I was around for the original key-signing ceremony for the PyPI TUF root keys which was live-streamed back in October 2020. Time flies, huh.

Writing Python like it's Rust: more robust code with type hints

This talk was given by Jakub Beránek about using type hints for more robust Python code. Having written a case-study on urllib3's adoption of type hints to find defects that testing and other tooling missed I highly recommend type hints for Python code as well:

Accelerating Python with Rust: The PyO3 Revolution

This talk was given by Roshan R Chandar about using PyO3 and Rust in Python modules.

Automatic Trusted Publishing with PyPI

This talk was given by Facundo Tuesca on using Trusted Publishing for authenticating with PyPI to publish packages.

Zero Trust APIs with Python

This talk was given by Jose Haro Peralta on how to design and implement secure web APIs using Python, data validation with Pydantic, and testing your APIs using tooling for detecting common security defects.

Best practices for securely consuming open source in Python

This talk was given by Cira Carey which highlights many of today's threats targetting open source consumers. Users should be aware of these when selecting projects to download and install.

Thanks for reading!♡ Did you find this article helpful and want more content like it? Get notified of new posts by subscribing to the RSS feed or the email newsletter.


This work is licensed under CC BY-SA 4.0

Real Python: Quiz: Python import: Advanced Techniques and Tips

$
0
0

In this quiz, you’ll test your understanding of Python’s import statement and related topics.

By working through this quiz, you’ll revisit how to use modules in your scripts and import modules dynamically at runtime.


[ 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 ]

Python Engineering at Microsoft: Python in Visual Studio Code – October 2024 Release

$
0
0

We’re excited to announce the October 2024 release of the Python and Jupyter extensions for Visual Studio Code!

This release includes the following announcements:

  • Run Python tests with coverage
  • Default Python problem matcher
  • Python language server mode

If you’re interested, you can check the full list of improvements in our changelogs for the Python, Jupyter and Pylance extensions.

Run Python tests with coverage

You can now run Python tests with coverage in VS Code! Test coverage is a measure of how much of your code is covered by your tests, which can help you identify areas of your code that are not being fully tested.

To run tests with coverage enabled, select the coverage run icon in the Test Explorer or the “Run with coverage” option from any menu you normally trigger test runs from. The Python extension will run coverage using the pytest-cov plugin if you are using pytest, or with coverage.py for unittest.

Note: Before running tests with coverage, make sure to install the correct testing coverage package for your project.

Once the coverage run is complete, lines will be highlighted in the editor for line level coverage. Test coverage results will appear as a “Test Coverage” sub-tab in the Test Explorer, which you can also navigate to with Testing: Focus on Test Coverage View in Command Palette (F1)). On this panel you can view line coverage metrics for each file and folder in your workspace.

Gif showing Python tests running with coverage.

For more information on running Python tests with coverage, see our Python test coverage documentation. For general information on test coverage, see VS Code’s Test Coverage documentation.

Default Python problem matcher

We are excited to announce support for one of our longest request features: there is now a default Python problem matcher! Aiming to simplifying issue tracking in your Python code and offering more contextual feedback, a problem matcher scans the task’s output for errors and warnings and displays them in the Problems panel, enhancing your development workflow. To integrate it, add "problemMatcher": "$python" to your tasks in task.json.

Below is an example of a task.json file that uses the default problem matcher for Python:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run Python",
            "type": "shell",
            "command": "${command:python.interpreterPath}",
            "args": [
                "${file}"
            ],
            "problemMatcher": "$python"
        }
    ]
}

For more information on tasks and problem matchers, visit VS Code’s Tasks documentation.

Pylance language server mode

There’s a new setting python.analysis.languageServerMode that enables you to choose between our current IntelliSense experience or a lightweight one that is optimized for performance. If you don’t require the full breadth of IntelliSense capabilities and prefer Pylance to be as resource-friendly as possible, you can set python.analysis.languageServerMode to light. Otherwise, to continue with the experience you have with Pylance today, you can leave out the setting entirely or explicitly set it to default .

This new functionality overrides the default values of the following settings:

Settinglight modedefault mode
“python.analysis.exclude”[“**”][]
“python.analysis.useLibraryCodeForTypes”falsetrue
“python.analysis.enablePytestSupport”falsetrue
“python.analysis.indexing”falsetrue

The settings above can still be changed individually to override the default values.

Shell integration in Python terminal REPL

The Python extension now includes a python.terminal.shellIntegration.enabled setting to enable a better terminal experience on MacOS and Linux machines. When enabled, this setting runs a PYTHONSTARTUP script before you launch the Python REPL in the terminal (for example, by typing and entering python), allowing you to leverage terminal shell integrations such as command decorations, re-run command and run recent commands.

Gif show shell integration enabled in the terminal.

Other Changes and Enhancements

We have also added small enhancements and fixed issues requested by users that should improve your experience working with Python and Jupyter Notebooks in Visual Studio Code. Some notable changes include:

  • Experimental Implement Abstract Classes with Copilot Code Action available for GitHub Copilot users using Pylance. Enable by adding "python.analysis.aiCodeActions": {"implementAbstractClasses": true} in your User settings.json
  • Fixed duplicate Python executable code when sending code to the Terminal REPL by using executeCommand rather than sendText for the activation command in @vscode#23929

We would also like to extend special thanks to this month’s contributors:

Try out these new improvements by downloading the Python extension and the Jupyter extension from the Marketplace, or install them directly from the extensions view in Visual Studio Code (Ctrl + Shift + X or ⌘ + ⇧ + X). You can learn more about Python support in Visual Studio Code in the documentation. If you run into any problems or have suggestions, please file an issue on the Python VS Code GitHub page.

The post Python in Visual Studio Code – October 2024 Release appeared first on Python.

Julien Tayon: PySimpleGUI : surviving the rug pull of licence part I

$
0
0
I liked pySimpleGUI, because as a coder that likes tkinter (the Tk/Tcl bindings) and as a former tcl/tk coder I enoyed the syntaxic sugar that was avoiding all the boiler plates required to build the application.

The main advantage was about not having to remember in wich order to make the pack and having to do the mainloop call. It was not a revolution, just a simple, elegant evolution, hence I was still feeling in control.

However, the projet made a jerk move by relicensing in full proprietary license that requires a key to work functionnaly.

I will not discuss this since the point have been made clearly on python mailing list.

Luckily I want to raise 2 points :
  • we have been numerous coders to fork the project for doing pull requests
  • it higlights once more the danger of too much dependencies


If you have a working copy of the repository



Well, you can still install a past version of pysimpleGUI, but unless you can do
pip install  git+https://github.com/jul/PySimpleGUI#egg=pysimpleGUI


Pro: if that version suited you, your old code will work
Con: there will be no update for the bugs and it is pretty much a no-go.

Expect free alternative



One of the power of free software is the power to fork, and some coders already forked in a « free forever » version of pysimpleGUI.
One of this fork is : Free Simple GUI.

Pro: migration is as simple as :

pip install FreeSimpleGUI
and then in the source :
- import PySimpleGUI as sg
+ import FreeSimpleGUI as sg

Con: a project is as useful as the capacity of the community to keep up with the job of solving issues and the strength of the community to follow up.

Migrating to tkinter



This will be covered in the week to come by translating some examples to real life migration by myself.

Since tkinter has improved a lot and his a pillar of python distribution when it is not broken by debian, it is fairly easy.

Pro: diminises the need for a dependency and empower you with the poweful concept of tk such as variables binded to a widget (an observer pattern).
Con: PySimpleGUI is a multi-target adaptor to not only tkinter but also remi (web), wx, Qt. If you were using the versatility of pysimpleGUI and its multi-platform features you really need to look at the « free forever » alternatives.

Julien Tayon: Simpler than PySimpleGUI and python tkinter: talking directly to tcl/tk

$
0
0
Well, the PySimpleGUI pull rug of licence reminded me how much dependencies are not a good thing.

Even though FreeSimpleGUI is a good approach to simpler tk/tcl binding in python : we can do better, especially if your linux distro split the python package and you don't have access to tkinter. I am watching you debian, splitting ALL packages and breaking them including ... tcl from tk (what a crime).

Under debian this stunt requires you to install tk :
apt install tk8.6


How hard is it to remove when tcl/tk is installed to do GUI programming in tk without tkinter?

Well, it's fairly easy, first and foremost coders are coders, they code in whatever language. If you do code in one language you can't do docker, simple sysadmin tasks (shell), compile C extensions (make syntax) or web applications (HTML + javascript). Hence, learning more than one language is part of doing python applications.

How hard is codinig in tcl/tk natively?

Fairly easy: it's difficulty is a little above lua, and way below perl thanks to the absence of references.

What value tcl have ?

It's still used in domain specific field such as VLSI (Very Large Scale Integration of electronic component).

So here is the plan : we are gonna do an application that do the math in python which is perfect for expressing complex math in more readable than tcl way and push all the GUI to the tk interpreter (albeit wish).

We are gonna make a simple wall clock ... and all tcl commands are injected to tcl through the puts function.
#!/usr/bin/env python
from subprocess import Popen, PIPE
from time import sleep, time, localtime

# let's talk to tk/tcl directly through p.stdin
p = Popen(['wish'], stdin=PIPE)

def puts(s):
    for l in s.split("\n"):
        p.stdin.write((l + "\n").encode())
        p.stdin.flush()

WIDTH=HEIGHT=400

puts(f"""
canvas .c -width {WIDTH} -height {HEIGHT} -bg white
pack .c
""")

# Constant are CAPitalized in python by convention
from cmath import  pi as PI, e as E
ORIG=complex(WIDTH/2, HEIGHT/2)

# correcting python notations j => I  
I = complex("j")
rad_per_sec = 2.0 * PI /60.0
rad_per_min = rad_per_sec / 60
rad_per_hour = rad_per_min / 12

origin_vector_hand = WIDTH/2 *  I

size_of_sec_hand = .9
size_of_min_hand = .8
size_of_hour_hand = .65

rot_sec = lambda sec : -E ** (I * sec * rad_per_sec )
rot_min = lambda min : -E ** (I *  min * rad_per_min )
rot_hour = lambda hour : -E ** (I * hour * rad_per_hour )

to_real = lambda c1,c2 : "%f %f %f %f" % (c1.real,c1.imag,c2.real, c2.imag)
for n in range(60):
    direction= origin_vector_hand * rot_sec(n)
    start=.9 if n%5 else .85
    puts(f".c create line {to_real(ORIG+start*direction,ORIG+.95*direction)}")
    sleep(.1)

diff_offset_in_sec = (time() % (24*3600)) - \
    localtime()[3]*3600 -localtime()[4] * 60.0 \
    - localtime()[5] 
n=0
while True:
    t = time()
    s= t%60
    m = m_in_sec = t%(60 * 60)
    h = h_in_sec = (t- diff_offset_in_sec)%(24*60*60)
    puts(".c delete second")
    puts(".c delete minute")
    puts(".c delete hour")
    c0=ORIG+ -.1 * origin_vector_hand * rot_sec(s)
    c1=ORIG+ size_of_sec_hand * origin_vector_hand * rot_sec(s)
    puts( f".c create line {to_real(c0,c1)} -tag second -fill blue -smooth true")
    c1=ORIG+size_of_min_hand * origin_vector_hand * rot_min(m)
    puts(f".c create line {to_real(ORIG, c1)} -tag minute -fill green -smooth true")
    c1=ORIG+size_of_hour_hand * origin_vector_hand * rot_hour(h)
    puts(f".c create line {to_real(ORIG,c1)} -tag hour -fill red -smooth true")
    sleep(.1)

Next time as a bonus, I'm gonna do something tkinter cannot do: bidirectional communications (REP/REQ pattern).

Chris Rose: uv, direnv, and simple .envrc files

$
0
0

I have adopted uv for a lot of Python development. I'm also a heavy user of direnv, which I like as a tool for setting up project-specific environments.

Much like Hynek describes, I've found uv sync to be fast enough to put into the chdir path for new directories. Here's how I'm doing it.

Direnv Libraries

First, it turns out you can pretty easily define custom direnv functions like the built-in ones (layout python, etc...). You do this by adding functions to ~/.config/direnv/direnvrc or in ~/.config/direnv/lib/ as shell scripts. I use this extensively to make my .envrc files easier to maintain and smaller. Now that I'm using uv here is my default for python:

functionuse_standard-python(){source_up_if_exists

dotenv_if_exists

source_env_if_exists.envrc.local

usevenv

uvsync
}

What does that even mean?

Let me explain each of these commands and why they are there:

  • source_up_if_exists -- this direnv stdlib function is here because I often group my projects into directories with common configuration. For example, when working on Chicon 8, I had a top level .envrc that set up the AWS configuration to support deploying Wellington and the Chicon 8 website. This searches up til it finds a .envrc in a higher directory, and uses that. source_up is the noisier, less-adaptable sibling.

  • dotenv_if_exists -- this loads .env from the current working directory. 12-factor apps often have environment-driven configuration, and docker compose uses them relatively seamlessly as well. Doing this makes it easier to run commands from my shell that behave like my development environment.

  • source_env_if_exists .envrc.local -- sometimes you need more complex functionality in a project than just environment variables. Having this here lets me use .envrc.local for that. This comes after .env because sometimes you want to change those values.

  • use venv -- this is a function that activates the project .venv (creating it if needed); I'm old and set in my ways, and I prefer . .venv/bin/activate.fish in my shell to the more newfangled "prefix it with a runner" mode.

  • uv sync -- this is a super fast, "install my development and main dependencies" command. This was way, way too slow with pip, pip-tools, poetry, pdm, or hatch, but with uv, I don't mind having this in my .envrc

Using it in a sentence

With this set up in direnv's configuration, all I need in my .envrc file is this:

usestandard-python

I've been using this pattern for a while now; it lets me upgrade how I do default Python setups, with project specific settings, easily.

Real Python: Quiz: Iterators and Iterables in Python: Run Efficient Iterations

$
0
0

In this quiz, you’ll test your understanding of Python’s Iterators and Iterables.

By working through this quiz, you’ll revisit how to create and work with iterators and iterables, understand the differences between them, and review how to use generator functions and the yield statement.


[ 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 ]


Julien Tayon: Bidirectionnal python/tk by talking to tk interpreter back and forth

$
0
0
Last time I exposed an old way learned in physical labs to do C or python/tk like in the old days: by summoning a tcl/tk interpreter and piping commands to it.

But what fun is it?

It's funnier if the tcl/tk interperpreter talks back to python :D as an hommage to the 25 years awaited TK9 versions that solves a lot of unicode trouble.

Beforehand, to make sense to the code a little warning is required : this code targets only POSIX environment and loses portability because I chose to use a way that is not the « one best way » for enabling bidirectionnal talks.

First and foremost, the Popen now use p.stdout=PIPE enabling the channel on which tcl will talk. As a joke puts/gets are named from tcl/tk functions and are used in python to push/get strings from tcl.

Instead of using multithreading having one thread listen to the output and putting the events in a local queue that the main thread will consume I chose the funniest technique of setting tcl/tk output non blocking which does not work on windows. This is the fnctl part of the code.

Then, I chose not to parse the output of tcl/tk but exec it, making tcl/tk actually push python commands back to python. That's the exec part of the code.

For this I needed an excuse : so I added buttons to change minutes/hours back and forth.

That's the moment we all are gonna agree that tcl/tk that tcl/tk biggest sin is its default look. Don't worry, next part is about using themes.

Compared to the first post, changes are minimal :D This is how it should look :
And here is the code, largely still below 100 sloc (by 3 lines).
#!/usr/bin/env python
from subprocess import Popen, PIPE
from time import sleep, time, localtime
import fcntl
import os

# let's talk to tk/tcl directly through p.stdin
p = Popen(['wish'], stdin=PIPE, stdout=PIPE)

fd = p.stdout.fileno()
flag = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)

def puts(s):
    for l in s.split("\n"):
        p.stdin.write((l + "\n").encode())
        p.stdin.flush()

def gets():
    ret=p.stdout.read()
    p.stdout.flush()
    return ret

WIDTH=HEIGHT=400

puts(f"""
canvas .c -width {WIDTH} -height {HEIGHT} -bg white
pack .c
. configure -background white

ttk::button  .ba -command {{  puts ch-=1 }} -text <<
pack .ba -side left   -anchor w
ttk::button .bb -command {{  puts cm-=1 }} -text  <
pack .bb -side left -anchor w
ttk::button .bc -command {{  puts ch+=1 }} -text >> 
pack .bc  -side right -anchor e
ttk::button .bd -command {{  puts cm+=1 }} -text > 
pack .bd  -side right -anchor e
""")

# Constant are CAPitalized in python by convention
from cmath import  pi as PI, e as E
ORIG=complex(WIDTH/2, HEIGHT/2)

# correcting python notations j => I  
I = complex("j")
rad_per_sec = 2.0 * PI /60.0
rad_per_min = rad_per_sec / 60
rad_per_hour = rad_per_min / 12

origin_vector_hand = WIDTH/2 *  I

size_of_sec_hand = .9
size_of_min_hand = .8
size_of_hour_hand = .65

rot_sec = lambda sec : -E ** (I * sec * rad_per_sec )
rot_min = lambda min : -E ** (I *  min * rad_per_min )
rot_hour = lambda hour : -E ** (I * hour * rad_per_hour )

to_real = lambda c1,c2 : "%f %f %f %f" % (c1.real,c1.imag,c2.real, c2.imag)
for n in range(60):
    direction= origin_vector_hand * rot_sec(n)
    start=.9 if n%5 else .85
    puts(f".c create line {to_real(ORIG+start*direction,ORIG+.95*direction)}")
    sleep(.01)

diff_offset_in_sec = (time() % (24*3600)) - \
    localtime()[3]*3600 -localtime()[4] * 60.0 \
    - localtime()[5] 
ch=cm=0
while True:
    # eventually parsing tcl output 
    back = gets()
    # trying is more concise than checking
    try:
        back = back.decode()
        exec(back)
    except Exception as e:
        pass

    t = time()
    s= t%60
    m = m_in_sec = t%(60 * 60) + cm * 60
    h = h_in_sec = (t- diff_offset_in_sec)%(24*60*60) + ch * 3600 + cm * 60
    puts(".c delete second")
    puts(".c delete minute")
    puts(".c delete hour")
    c0=ORIG+ -.1 * origin_vector_hand * rot_sec(s)
    c1=ORIG+ size_of_sec_hand * origin_vector_hand * rot_sec(s)
    puts( f".c create line {to_real(c0,c1)} -tag second -fill blue -smooth true")
    c1=ORIG+size_of_min_hand * origin_vector_hand * rot_min(m)
    puts(f".c create line {to_real(ORIG, c1)} -tag minute -fill green -smooth true")
    c1=ORIG+size_of_hour_hand * origin_vector_hand * rot_hour(h)
    puts(f".c create line {to_real(ORIG,c1)} -tag hour -fill red -smooth true")
    puts("flush stdout")
    sleep(.1)


Some history about this code.



I have been mentored in a physical lab where we where doing the pipe, fork, dup2 dance to tcl/tk from C to give a nice output to our simulations so we could control our instuition was right and could extract pictures for the publications. This is a trick that is almost as new as my arteries.
My mentor used to say : we are not coders, we need stuff to work fast and neither get drowned in computer complexity or endless quest for « the one best way » nor being drowned in bugs, we aim for the Keep It Simple Stupid Ways.

Hence, this is a Keep It Simple Stupid approach that I revived for the sake of seeing if it was still robust after 35 years without using it.

Well, if it's robust and it's working: it ain't stupid even if it isn't the « one best idiomatic way ». :P

Talk Python to Me: #479: Designing Effective Load Tests for Your Python App

$
0
0
You're about to launch your new app or API, or even just a big refactor of your current project. Will it stand up and deliver when you put it into production or when that big promotion goes live? Or will it wither and collapse? How would you know? Well you would test that of course. We have Anthony Shaw back on the podcast to dive into a wide range of tools and techniques for performance and loading testing of web apps.<br/> <br/> <strong>Episode sponsors</strong><br/> <br/> <a href='https://talkpython.fm/sentry'>Sentry Error Monitoring, Code TALKPYTHON</a><br> <a href='https://talkpython.fm/workos'>WorkOS</a><br> <a href='https://talkpython.fm/training'>Talk Python Courses</a><br/> <br/> <strong>Links from the show</strong><br/> <br/> <div><b>Anthony on Twitter</b>: <a href="https://twitter.com/anthonypjshaw?featured_on=talkpython" target="_blank">@anthonypjshaw</a><br/> <b>Anthony's PyCon Au Talk</b>: <a href="https://www.youtube.com/watch?v=or3PbMGMz4o" target="_blank">youtube.com</a><br/> <b>locust load testing tool</b>: <a href="https://locust.io?featured_on=talkpython" target="_blank">locust.io</a><br/> <b>playwright</b>: <a href="https://playwright.dev?featured_on=talkpython" target="_blank">playwright.dev</a><br/> <b>mimesis</b>: <a href="https://github.com/lk-geimfari/mimesis?featured_on=talkpython" target="_blank">github.com</a><br/> <b>mimesis providers</b>: <a href="https://mimesis.name/en/master/providers.html?featured_on=talkpython" target="_blank">mimesis.name</a><br/> <b>vscode pets</b>: <a href="https://marketplace.visualstudio.com/items?itemName=tonybaloney.vscode-pets&featured_on=talkpython" target="_blank">marketplace.visualstudio.com</a><br/> <b>vscode power-mode</b>: <a href="https://marketplace.visualstudio.com/items?itemName=hoovercj.vscode-power-mode&featured_on=talkpython" target="_blank">marketplace.visualstudio.com</a><br/> <b>opentelemetry</b>: <a href="https://opentelemetry.io?featured_on=talkpython" target="_blank">opentelemetry.io</a><br/> <b>uptime-kuma</b>: <a href="https://github.com/louislam/uptime-kuma?featured_on=talkpython" target="_blank">github.com</a><br/> <b>Talk Python uptime / status</b>: <a href="https://talkpython.fm/status" target="_blank">talkpython.fm/status</a><br/> <b>when your serverless computing bill goes parabolic...</b>: <a href="https://www.youtube.com/watch?v=SCIfWhAheVw" target="_blank">youtube.com</a><br/> <b>Watch this episode on YouTube</b>: <a href="https://www.youtube.com/watch?v=W6UVq8zVtxU" target="_blank">youtube.com</a><br/> <b>Episode transcripts</b>: <a href="https://talkpython.fm/episodes/transcript/479/designing-effective-load-tests-for-your-python-app" target="_blank">talkpython.fm</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">youtube.com</a><br/> <b>Follow Talk Python on Mastodon</b>: <a href="https://fosstodon.org/web/@talkpython" target="_blank"><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"><i class="fa-brands fa-mastodon"></i>mkennedy</a><br/></div>

Mariatta: Python Core Sprint 2024: Day 5

$
0
0

Python Core Sprint 2024: Day 5

Datetime and Hypothesis

I reviewed some issues that came to the CPython repo. There were a few interesting tickets related to the datetime module. These issues were discovered by Hypothesis, a property-based testing tool for Python. I’ve been hearing a lot about Hypothesis, but never really used it in production or at work. I watched a talk about it at PyCon US many years ago, and I even had ice cream selfie with Zac who maintains Hypothesis. Anyway, I’ve just been interested in learning more about Hypothesis and how it could solve issues not caught by other testing methods, and I think this is one of the perks of contributing to open source: getting exposed to things you don’t normally use at work, and I think it’s a great way to learn new things.

Zato Blog: API Testing in Pure English

$
0
0

API Testing in Pure English

How to test APIs in pure English

Do you have 20 minutes to learn how to test APIs in pure English, without any programming needed?

Great, the API testing tutorial is here.

Right after you complete it, you'll be able to write API tests as the one below.

Next steps:

➤ Read about how to use Python to build and integrate enterprise APIs that your tests will cover
➤ Python API integration tutorial
Python Integration platform as a Service (iPaaS)
What is an Enterprise Service Bus (ESB)? What is SOA?

Julien Tayon: Writing an interactive tcl/tk interpreter proxy to wish in python

$
0
0
Maybe, you want to experiment small stuffs in wish (the tcl/tk) interpreter because of a post claiming that direct python tcl/tk is simpler in some simple cases than tkinter.

As a convinced tkinter/FreeSimpleGUI user, I see this as an extreme claim that require solid evidences.

When all is said and done, wish interpreter is not interactive, and for testing simple stuff it can get annoying very fast. Thus, it would be nice to add readline to the interface.

So here is a less than 100 line of code exercice of soing exactly so while having fun with : readline and multiprocessing (I would have taken multithreading if threads were easy to terminate).

Readline I quote
The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter.
Basically, it adds arrow navigation in history, back search with Ctrl+R, Ctrl+K for cuting on the right, Ctrl+Y for yanking ... all the facilities of interaction you have in bash or ipython for instance.

We are gonna use multiprocessing because tcl/tl is event oriented, hence, asynchronuous hence, we may have string coming from the tcl stdout while we do nothing and we would like to print them.

We also introduce like in ipython some magic prefixed with # (comment in tcl) like #? for the help. A session should look like this :
# pack [ button .c -text that -command { puts "hello" } ]
# 
tcl output> hello # here we pressed the button "that"
tcl output> hello # here we pressed the button "that"


# set name 32
# puts $name

tcl output> 32

# #?

#l print current recorded session
#? print current help
#! calls python code like
  #!save(name="temp") which saves the current session in current dir in "temp" file
bye exit quit quit the current session

# #l
pack [ button .c -text that -command { puts "hello" } ]
set name 32
puts $name

# #!save("my_test.tcl")
# quit
The code in itself is fairly easy to read the only catch is that wish accepts multiline input. I can't because I don't know how to parse tcl. As a result I « eval in tcl » every line to know if there is an error and ask politely tcl to do the job of signaling the error with a « catch/error (the equivalent of python try + raise an exception).
#!/usr/bin/env python3
# -*- coding: utf8 -*-

from subprocess import Popen, PIPE, STDOUT
from multiprocessing import Process as Thread
import sys, os
import atexit
import os
import readline
from time import sleep

### interactive session with history with readline
histfile = os.path.join(os.path.expanduser("~"), ".wish_history")
try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(-1)
except FileNotFoundError:
    pass

### saving history at the end of the session
atexit.register(readline.write_history_file, histfile)

### opening wish
gs = Popen(['wish'], 
        stdin=PIPE,
        stdout=PIPE,
        stderr=PIPE,
        bufsize=-1,
        )

os.set_blocking(gs.stdout.fileno(), False)
os.set_blocking(gs.stderr.fileno(), False)
os.set_blocking(gs.stdin.fileno(), False)

def puts(s):
    out = f"""set code [ catch {{ {s} }} p ]
if {{$code}} {{ error $p }}
"""
    gs.stdin.write(out.encode())
    gs.stdin.flush()
    gs.stdin.write(( "flush stdout\n").encode())
    sleep(.1)

def gets():
    while True:
        gs.stdout.flush()
        tin = gs.stdout.read()
        if tin:
            print("\ntcl output>" + tin.decode())
        sleep(.1)

def save(fn="temp"):
    open(fn,"wt").write(session)

session=s=""

# async io in tcl requires a background process to read the tcl output
t =Thread(target=gets, args=())
t.start()

while True:
    s = input("# ")
    if s in { "bye", "quit", "exit" }:
        t.terminate()
        gs.stdin.write("destroy .".encode())
        break
    elif s == "#l":
        print(session)
    elif s == "#?":
        print("""
#l print current recorded session
#? print current help
#! calls python code like
  #!save(name="temp") which saves the current session in current dir in "temp" file
bye exit quit quit the current session
""" )
        continue
    elif s.startswith("#!"):
        print(eval(s[2:]))
        continue
    else:
        puts(s)
        if err:=gs.stderr.readline():
            sys.stderr.write(err.decode())
        else:
            if s and not s.startswith("#"):
                session += s + "\n"

Real Python: Python News Roundup: October 2024

$
0
0

October is always an important month for Python, as this is when a new major version is released. Python 3.13 is the new version this year, and it brings several new features that lay the groundwork for other changes in the future. As one version of Python comes to life, another is put to rest. Python 3.8 is already five years old, which means that this version won’t be supported any longer.

There are also exciting developments happening in the wider Python community. In this newsletter, you can read about Polars’ improved support for plotting, as well as how Django developers gathered for the annual DjangoCon US conference.

Time to jump in and read about what’s happening in the world of Python!

Python 3.13 Release Slightly Delayed

The release of Python 3.13, the newest version of Python, was originally scheduled for October 1, 2024. However, a few days before that date, release manager Thomas Wouters decided to postpone the release until October 7, 2024:

I’m a little concerned with the impact of the incremental GC change in 3.13, which recently showed up. It’s not clear that the incremental GC provides significant improvements (although the smaller pauses are probably desirable), it clearly has slightly more overhead in common cases, and we’re still discovering pathological cases.

I don’t think we should release 3.13.0 with the incremental GC. (Source)

The incremental garbage collector was a small improvement slated for Python 3.13. In many cases, the new garbage collection algorithm improves performance. Unfortunately, it was found to slow down Python significantly in some rare cases.

As a result, the core developers decided to revert the implementation and use the traditional garbage collector in Python 3.13. At the same time, the new implementation is being scrutinized and currently the goal is to include incremental garbage collection in Python 3.14.

Delaying a major Python release is never an easy choice. However, erring on the side of caution is a good approach, and it’s great to see that the Python 3.13 release is being handled responsibly.

Python 3.13 Highlights

As always, a new Python release brings many improvements and new features. You can explore these in-depth in Python 3.13: Cool New Features for You to Try. In particular, the new release includes:

  • A brand new interactive interpreter (REPL)
  • Colored tracebacks and improved error messages
  • A separate, free-threaded version of Python that runs without the global interpreter lock (GIL)
  • An experimental just-in-time (JIT) compiler
  • Several improvements to Python’s static type system

For free threading and the JIT compiler, you need to compile Python with special build flags. Read Python 3.13 Preview: Free Threading and a JIT Compiler to learn more about how to explore these two new features. Additionally, Python 3.13 Preview: A Modern REPL provides more detail on the new REPL.

Read the full article at https://realpython.com/python-news-october-2024/ »


[ 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 ]

Python Bytes: #404 The Lost Episode

$
0
0
<strong>Topics covered in this episode:</strong><br> <ul> <li><strong><a href="https://www.python.org/downloads/release/python-3130/?featured_on=pythonbytes">Python 3.13.0 released Oct 7</a></strong></li> <li><strong><a href="https://peps.python.org/pep-0759/?featured_on=pythonbytes">PEP 759 – External Wheel Hosting</a></strong></li> <li><strong><a href="https://pypi.org/project/pytest-freethreaded/?featured_on=pythonbytes">pytest-freethreaded</a></strong></li> <li><strong><a href="https://github.com/MrMino/pytest-edit?featured_on=pythonbytes">pytest-edit</a></strong></li> <li><strong>Extras</strong></li> <li><strong>Joke</strong></li> </ul><a href='https://www.youtube.com/watch?v=6w3-YkKMJ0E' style='font-weight: bold;'data-umami-event="Livestream-Past" data-umami-event-episode="404">Watch on YouTube</a><br> <p><strong>About the show</strong></p> <p>Sponsored by ScoutAPM: <a href="https://pythonbytes.fm/scout"><strong>pythonbytes.fm/scout</strong></a></p> <p><strong>Connect with the hosts</strong></p> <ul> <li>Michael: <a href="https://fosstodon.org/@mkennedy"><strong>@mkennedy@fosstodon.org</strong></a></li> <li>Brian: <a href="https://fosstodon.org/@brianokken"><strong>@brianokken@fosstodon.org</strong></a></li> <li>Show: <a href="https://fosstodon.org/@pythonbytes"><strong>@pythonbytes@fosstodon.org</strong></a></li> </ul> <p>Join us on YouTube at <a href="https://pythonbytes.fm/stream/live"><strong>pythonbytes.fm/live</strong></a> to be part of the audience. Usually <strong>Monday</strong> at 10am PT. Older video versions available there too.</p> <p>Finally, if you want an artisanal, hand-crafted digest of every week of the show notes in email form? Add your name and email to <a href="https://pythonbytes.fm/friends-of-the-show">our friends of the show list</a>, we'll never share it. </p> <p><strong>Brian #1:</strong> <a href="https://www.python.org/downloads/release/python-3130/?featured_on=pythonbytes">Python 3.13.0 released Oct 7</a></p> <ul> <li>That’s today!</li> <li><a href="https://docs.python.org/3.13/whatsnew/3.13.html?featured_on=pythonbytes">What’s New In Python 3.13</a> <ul> <li>Interpreter (REPL) improvements <ul> <li>exit works (really, this is worth the release right here)</li> <li>Multiline editing with history preservation. <ul> <li>history sticks around between sessions</li> </ul></li> <li>Direct support for REPL-specific commands like help, exit, and quit, without the need to call them as functions.</li> <li>Prompts and tracebacks with color enabled by default.</li> <li>Interactive help browsing using F1 with a separate command history.</li> <li>History browsing using F2 that skips output as well as the &gt;&gt;&gt; and … prompts.</li> <li>“Paste mode” with F3 that makes pasting larger blocks of code easier (press F3 again to return to the regular prompt).</li> <li>exit now works without parens</li> </ul></li> <li>Improved error messages <ul> <li>Colorful tracebacks</li> <li>Better messages for <ul> <li>naming a script/module the same name as a stdlib module.</li> <li>naming a script/module the same name as an installed third party module.</li> <li>misspelling a keyword argument</li> </ul></li> </ul></li> <li>Free threaded CPython <ul> <li>Included in official installers on <a href="https://docs.python.org/3.13/using/windows.html#install-freethreaded-windows">Windows</a> and <a href="https://docs.python.org/3.13/using/mac.html#install-freethreaded-macos">macOS</a> <ul> <li>Read these links to figure out how - it’s not turned on by default</li> </ul></li> </ul></li> <li>Lot’s more. see the What’s new page</li> </ul></li> </ul> <p><strong>Michael #2:</strong> <a href="https://peps.python.org/pep-0759/?featured_on=pythonbytes">PEP 759 – External Wheel Hosting</a></p> <ul> <li>pypi.org ships <a href="https://www.fastly.com/customers/python-software-foundation/?featured_on=pythonbytes">over 66 petabytes / month</a> backed by Fastly</li> <li>There are hard project size limits for publishers to PyPI</li> <li>We can host the essence of a <strong>.whl</strong> as a <strong>.rim</strong> file, then allow an external download URL</li> <li>Security: Several factors as described in this proposal should mitigate security concerns with externally hosted wheels, such as: <ul> <li>Wheel file checksums <strong>MUST</strong> be included in .rim files, and once uploaded cannot be changed. Since the checksum stored on PyPI is immutable and required, it is not possible to spoof an external wheel file, even if the owning organization lost control of their hosting domain.</li> <li>Externally hosted wheels <strong>MUST</strong> be served over HTTPS.</li> <li>In order to serve externally hosted wheels, organizations <strong>MUST</strong> be approved by the PyPI admins.</li> </ul></li> </ul> <p><strong>Brian #3:</strong> <a href="https://pypi.org/project/pytest-freethreaded/?featured_on=pythonbytes">pytest-freethreaded</a></p> <ul> <li>PyCon JP 2024 Team: <ul> <li>This extension was created at PyCon JP sprints with <a href="https://github.com/tonybaloney/pytest-freethreaded/blob/main/README.md#credits">Anthony Shaw and 7 other folks listed in credits.</a></li> </ul></li> <li>“A pytest plugin for helping verify that your tests and libraries are thread-safe with the Python 3.13 experimental freethreaded mode.”</li> <li>Testing your project for compatibility with freethreaded Python. <ul> <li>Testing in single thread doesn’t test that.</li> <li>Neither does testing with pytest-xdist, because it uses multiprocessing to parallelize tests.</li> <li>So, Ant and others “made this plugin to help you run your tests in a thread-pool with the GIL disabled, to help you identify if your tests are thread-safe.”</li> <li>“And the first library we tested it on (which was marked as compatible) caused a segmentation fault in CPython! So you should give this a go if you're a package maintainer.”</li> </ul></li> </ul> <p><strong>Michael #4:</strong> <a href="https://github.com/MrMino/pytest-edit?featured_on=pythonbytes">pytest-edit</a></p> <ul> <li>A simple Pytest plugin for opening editor on the failed tests.</li> <li>Type <code>pytest --edit</code> to open the failing test code <img src="https://paper.dropboxstatic.com/static/img/ace/emoji/2728.png?version=8.0.0" alt="sparkles" /></li> <li>Be sure to set your favorite editor in the ENV variables</li> </ul> <p><strong>Extras</strong> </p> <p>Michael:</p> <ul> <li><a href="https://training.talkpython.fm/courses/all?featured_on=pythonbytes">New way to explore</a> Talk Python courses via topics <ul> <li>This has been in our <a href="https://training.talkpython.fm/apps?featured_on=pythonbytes">mobile apps</a> since their rewrite but finally comes to <a href="https://training.talkpython.fm/courses/all?featured_on=pythonbytes">the web</a></li> </ul></li> <li><a href="https://mkennedy.codes/posts/lets-go-easy-on-pypi-ok/?featured_on=pythonbytes">Let's go easy on PyPI, OK? essay</a></li> <li>Hynek’s video: <a href="https://www.youtube.com/watch?v=8UuW8o4bHbw">uv IS the Future of Python Packaging </a><a href="https://www.youtube.com/watch?v=8UuW8o4bHbw"><img src="https://paper.dropboxstatic.com/static/img/ace/emoji/1f40d.png?version=8.0.0" alt="snake" /></a><a href="https://www.youtube.com/watch?v=8UuW8o4bHbw"><img src="https://paper.dropboxstatic.com/static/img/ace/emoji/1f4e6.png?version=8.0.0" alt="package" /></a></li> <li><a href="https://github.com/adamchainz/djade-pre-commit?featured_on=pythonbytes">djade-pre-commit</a></li> <li>Polyfill.io, BootCDN, Bootcss, Staticfile attack <a href="https://www.bleepingcomputer.com/news/security/polyfillio-bootcdn-bootcss-staticfile-attack-traced-to-1-operator/?featured_on=pythonbytes">traced to 1 operator</a></li> <li><a href="https://purgecss.com/CLI.html?featured_on=pythonbytes">PurgeCSS CLI</a> </li> <li><a href="https://blog.python.org/2024/10/python-3127-released.html?featured_on=pythonbytes">Python 3.12.7 released</a></li> <li><a href="https://discuss.python.org/t/incremental-gc-and-pushing-back-the-3-13-0-release/65285/1?featured_on=pythonbytes">Incremental GC and pushing back the 3.13.0 release</a></li> <li><a href="https://fosstodon.org/@midnitte/113239548093653991">uv making the rounds</a></li> <li><a href="https://fosstodon.org/@mkennedy/113247714541010618">LLM fatigue</a>, is it real?</li> <li>Take the <a href="https://survey.alchemer.com/s3/8009809/l-python-developers-survey-2024/?utm_source=pythonbytespodcast">Python Developers Survey 2024</a></li> </ul> <p><strong>Joke:</strong> <a href="https://inzonedesign.com/blog/28-cleverly-funny-creative-404-error-pages/?featured_on=pythonbytes">Funny 404 pages</a></p> <ul> <li>We have <a href="https://pythonbytes.fm/not-found-page-or-something">something at least interesting at pythonbytes.fm</a></li> </ul>

Python Insider: Python 3.13.0 (final) released

$
0
0

 

Python 3.13.0 is now available



This is the stable release of Python 3.13.0

Python 3.13.0 is the newest major release of the Python programming language, and it contains many new features and optimizations compared to Python 3.12. (Compared to the last release candidate, 3.13.0rc3, 3.13.0 contains two small bug and some documentation and testing changes.)

Major new features of the 3.13 series, compared to 3.12

Some of the new major new features and changes in Python 3.13 are:

New features

Typing

Removals and new deprecations

  • PEP 594 (Removing dead batteries from the standard library) scheduled removals of many deprecated modules: aifcaudioopchunkcgicgitbcryptimghdrmailcapmsilibnisnntplibossaudiodevpipessndhdrspwdsunautelnetlibuuxdrliblib2to3.
  • Many other removals of deprecated classes, functions and methods in various standard library modules.
  • C API removals and deprecations. (Some removals present in alpha 1 were reverted in alpha 2, as the removals were deemed too disruptive at this time.)
  • New deprecations, most of which are scheduled for removal from Python 3.15 or 3.16.

For more details on the changes to Python 3.13, see What’s new in Python 3.13.

More resources

We hope you enjoy the new releases!

Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation.

Choo-choo from the release train,

Your release team,
Thomas Wouters 
Ned Deily 
Steve Dower 
Łukasz Langa 

Python Morsels: Python 3.13's best new features

$
0
0

Python 3.13 comes with a brand new REPL and improvements to virtual environments and the Python debugger.

Important but not my favorite

First, I'd like to note that I'm not going to talk about the experimental free-threaded mode, the experimental just-in-time compilation option, or many other features that don't affect most Python developers today.

Instead, let's focus on some of the more fun things.

The New Python REPL

My favorite feature by far …

Read the full article: https://www.pythonmorsels.com/python-313-whats-new/

Python Anywhere: Serving UTF-8 static files? Headers to the rescue (an epic tutorial)!

$
0
0

Imagine there’s a PythonAnywhere user, homer8bc, with poetic inclinations. He wants to serve his newest poem (he believes it’s quite epic) as a static text page. He’s old school — he doesn’t believe in HTML, and as for CSS? Forget it! His friend, S. Yodos, lives in Cyme, while homer8bc resides on Ios island, so in-person communication is difficult…

Python Software Foundation: Join the Python Developers Survey 2024: Share your experience!

$
0
0

This year we are conducting the eighth iteration of the official Python Developers Survey. The goal is to capture the current state of the language and the ecosystem around it. By comparing the results with last year’s, we can identify and share with everyone the hottest trends in the Python community and the key insights into it.

We encourage you to contribute to our community’s knowledge by sharing your experience and perspective. Your participation is valued! The survey should only take you about 10-15 minutes to complete.

Contribute to the Python Developers Survey 2024!


This year we aim to reach even more of our community and ensure accurate global representation by highlighting our localization efforts:

  • The survey is translated into Spanish, Portuguese, Chinese, Korean, Japanese, German, French and Russian. It has been translated in years past, as well, but we plan to be louder about the translations available this year!
  • To assist individuals in promoting the survey and encouraging their local communities and professional networks we have created a Promotion Kit with images and social media posts translated into a variety of languages. We hope this promotion kit empowers folks to spread the invitation to respond to the survey within their local communities.
    • We’d love it if you’d share one or more of the posts below to your social media or any community accounts you manage, as well as share the information in discords, mailing lists, or chats you participate in.
    • If you would like to help out with translations you see are missing, please request edit access to the doc and share what language you will be translating to. Translation into languages the survey may not be translated to is also welcome.
  • If you have ideas about what else we can do to get the word out and encourage a diversity of responses, please comment on the corresponding Discuss thread.


The survey is organized in partnership between the Python Software Foundation and JetBrains. After the survey is over, we will publish the aggregated results and randomly choose 20 winners (among those who complete the survey in its entirety), who will each receive a $100 Amazon Gift Card or a local equivalent.

Django Weblog: Django bugfix release issued: 5.1.2

$
0
0

Today we've issued the 5.1.2 bugfix release.

The release package and checksums are available from our downloads page, as well as from the Python Package Index. The PGP key ID used for this release is Natalia Bidart: 2EE82A8D9470983E.

Viewing all 23442 articles
Browse latest View live