Planet Python

Subscribe to Planet Python feed
Planet Python - http://planetpython.org/
Updated: 12 hours 21 min ago

TechBeamers Python: Pass by Reference vs Pass by Value in Python

Sat, 2024-09-07 06:59

Is Python pass by reference or pass by value? This question intrigues every Python programmer coming from a C or Java background. In this tutorial, you will get its answer and learn the meaning of “pass by reference” and “pass by value” along with their difference in Python. Python Pass by Reference vs Pass by […]

The post Pass by Reference vs Pass by Value in Python appeared first on TechBeamers.

Categories: FLOSS Project Planets

Python Insider: Python 3.13.0RC2, 3.12.6, 3.11.10, 3.10.15, 3.9.20, and 3.8.20 are now available!

Sat, 2024-09-07 06:24

Hi there!
A big joint release today. Mostly security fixes but we also have the final release candidate of 3.13 so let’s start with that!

Python 3.13.0RC2

Final opportunity to test and find any show-stopper bugs before we bless and release 3.13.0 final on October 1st.

Get it here: Python Release Python 3.13.0rc2 | Python.org

Call to action

We strongly encourage maintainers of third-party Python projects to prepare their projects for 3.13 compatibilities during this phase, and where necessary publish Python 3.13 wheels on PyPI to be ready for the final release of 3.13.0. Any binary wheels built against Python 3.13.0rc2 will work with future versions of Python 3.13. As always, report any issues to the Python bug tracker.

Please keep in mind that this is a preview release and while it’s as close to the final release as we can get it, its use is not recommended for production environments.

Core developers: time to work on documentation now
  • Are all your changes properly documented?
  • Are they mentioned in What’s New?
  • Did you notice other changes you know of to have insufficient documentation?

As a reminder, until the final release of 3.13.0, the 3.13 branch is set up so that the Release Manager (@thomas) has to merge the changes. Please add him (@Yhg1s on GitHub) to any changes you think should go into 3.13.0. At this point, unless something critical comes up, it should really be documentation only. Other changes (including tests) will be pushed to 3.13.1.

New features in Python 3.13 Python 3.12.6

This is an expedited release for 3.12 due to security content. The schedule returns back to regular programming in October.

One notable change for macOS users: as mentioned in the previous release of 3.12, this release drops support for macOS versions 10.9 through 10.12. Versions of macOS older than 10.13 haven’t been supported by Apple since 2019, and maintaining support for them has become too difficult. (All versions of Python 3.13 have already dropped support for them.)

Get it here: Python Release Python 3.12.6 | Python.org

92 commits.

Python 3.11.10

Python 3.11 joins the elite club of security-only versions with no binary installers.

Get it here: Python Release Python 3.11.10 | Python.org

28 commits.

Python 3.10.15

Get it here: Python Release Python 3.10.15 | Python.org

24 commits.

Python 3.9.20

Get it here: Python Release Python 3.9.20 | Python.org

22 commits.

Python 3.8.20

Python 3.8 is very close to End of Life (see the Release Schedule). Will this be the last release of 3.8 ever? We’ll see… but now I think I jinxed it.

Get it here: Python Release Python 3.8.20 | Python.org

22 commits.

Security content in today’s releases
  • gh-123678 and gh-116741: Upgrade bundled libexpat to 2.6.3 to fix CVE-2024-28757, CVE-2024-45490, CVE-2024-45491 and CVE-2024-45492.
  • gh-118486: os.mkdir() on Windows now accepts mode of 0o700 to restrict the new directory to the current user. This fixes CVE-2024-4030 affecting tempfile.mkdtemp() in scenarios where the base temporary directory is more permissive than the default.
  • gh-123067: Fix quadratic complexity in parsing "-quoted cookie values with backslashes by http.cookies. Fixes CVE-2024-7592.
  • gh-113171: Fixed various false positives and false negatives in IPv4Address.is_private, IPv4Address.is_global, IPv6Address.is_private, IPv6Address.is_global. Fixes CVE-2024-4032.
  • gh-67693: Fix urllib.parse.urlunparse() and urllib.parse.urlunsplit() for URIs with path starting with multiple slashes and no authority. Fixes CVE-2015-2104.
  • gh-121957: Fixed missing audit events around interactive use of Python, now also properly firing for python -i, as well as for python -m asyncio. The event in question is cpython.run_stdin.
  • gh-122133: Authenticate the socket connection for the socket.socketpair() fallback on platforms where AF_UNIX is not available like Windows.
  • gh-121285: Remove backtracking from tarfile header parsing for hdrcharset, PAX, and GNU sparse headers. That’s CVE-2024-6232.
  • gh-114572: ssl.SSLContext.cert_store_stats() and ssl.SSLContext.get_ca_certs() now correctly lock access to the certificate store, when the ssl.SSLContext is shared across multiple threads.
  • gh-102988: email.utils.getaddresses() and email.utils.parseaddr() now return ('', '') 2-tuples in more situations where invalid email addresses are encountered instead of potentially inaccurate values. Add optional strict parameter to these two functions: use strict=False to get the old behavior, accept malformed inputs. getattr(email.utils, 'supports_strict_parsing', False) can be use to check if the strict paramater is available. This improves the CVE-2023-27043 fix.
  • gh-123270: Sanitize names in zipfile.Path to avoid infinite loops (gh-122905) without breaking contents using legitimate characters. That’s CVE-2024-8088.
  • gh-121650: email headers with embedded newlines are now quoted on output. The generator will now refuse to serialize (write) headers that are unsafely folded or delimited; see verify_generated_headers. That’s CVE-2024-6923.
  • gh-119690: Fixes data type confusion in audit events raised by _winapi.CreateFile and _winapi.CreateNamedPipe.
  • gh-116773: Fix instances of <_overlapped.Overlapped object at 0xXXX> still has pending operation at deallocation, the process may crash.
  • gh-112275: A deadlock involving pystate.c’s HEAD_LOCK in posixmodule.c at fork is now fixed.
Stay safe and upgrade!

Upgrading is highly recommended to all users of affected versions.

Thank you for your support

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.


Łukasz Langa @ambv
on behalf of your friendly release team,

Ned Deily @nad
Steve Dower @steve.dower
Pablo Galindo Salgado @pablogsal
Łukasz Langa @ambv
Thomas Wouters @thomas

 

 

Categories: FLOSS Project Planets

Python Morsels: Creating Python programs

Fri, 2024-09-06 14:21

Python programs are created in code editors, and can be run using system command prompt.

Table of contents

  1. The Python REPL
  2. Definitions: program, script, command-line, editor
  3. Creating a Python program in a code editor
  4. Running our Python program
  5. Printing to see program output
  6. Python programs are not launched from the REPL
  7. Different operating systems
  8. Python scripts are run from the command prompt or terminal

The Python REPL

This is the Python REPL, also known as the Interactive Python Interpreter:

>>>

How can I tell it's the Python REPL?

Well, the prompt shows three greater than signs (>>>), which indicates that we're in the Python REPL.

Typing all of your code in the Python REPL is pretty limiting.

Our code disappears right after we've typed it. Also, if we'd like someone to be able to import our code as a module, they can't.

Definitions: program, script, command-line, editor

Let's make a Python program.

Read the full article: https://www.pythonmorsels.com/creating-python-programs/
Categories: FLOSS Project Planets

Django Weblog: Djangonaut Space - New session 2024

Fri, 2024-09-06 12:33

We are thrilled to announce that Djangonaut Space, a mentorship program, is open for applicants for our next cohort!

Djangonaut Space is holding a third session this year! This session will start on October 14th, 2024. We are accepting applications until September 14th, 2024. More details can be found in the website.

Djangonaut Space is a free, 8-week group mentoring program where individuals will work self-paced in a semi-structured learning environment. It seeks to help members of the community who wish to level up their current Django code contributions and potentially take on leadership roles in Django in the future.

“I signed up for this program with the goal of starting my journey as a contributor, but I ended up gaining so much more. In this community, I found incredible people who not only guide you toward solutions but also encourage and celebrate every achievement along the way.” - Raffaella, Djangonaut

If you have questions, they are holding an AMA session on Zoom next week. See their social media account for more details:

Categories: FLOSS Project Planets

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

Fri, 2024-09-06 09:50

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

This release includes the following announcements:

  • Django unit test support
  • Go to definition from inlay hints with Pylance

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

Django unit test support

We are excited to announce support for one of our most requested features: you can now discover and run Django unit tests through the Test Explorer!

In order to enable this feature, you will need to add a MANAGE_PY_PATH environment variable, pointing to your Django application’s manage.py file. To do so, you can follow these steps:

  1. Set "python.testing.unittestEnabled": true, in your settings.json file.
  2. Add MANAGE_PY_PATH as an environment variable:
    1. Create a .env file at the root of your project.
    2. Add MANAGE_PY_PATH='<path-to-manage.py>' to the .env file, replacing <path-to-manage.py> with the path to your application’s manage.py file.

      Tip: You can copy the path by right clicking on the file in the Explorer view and selecting Copy Path.

  3. Add Django test arguments to "python.testing.unittestArgs": [] in the settings.json file as needed, and remove any arguments that are not compatible with Django.

Note: By default, the Python extension looks for and loads .env files at the project root. If your .env file is not at the project root or you are using VS Code variable substitution, add "python.envFile": "${workspaceFolder}/<path-to-.env>" to your settings.json file, so the Python extension can load the environment variables in this file when running and discovering tests. See our Python environment variables docs for more information on environment variables.

Navigate to the Testing view, and select the Refresh Tests button to have your Django tests displayed!

For troubleshooting tips, please see our Django testing docs. As you explore this newly added feature, please provide feedback and report any issues in our vscode-python repo or by using the Python: Report Issue command.

Go to definition from inlay hints with Pylance

When enabling inlay hints with Pylance, you can now more conveniently navigate to a type’s definition through Ctrl+Click or Cmd+Click when hovering over it.

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:

Call for Community Feedback

As we are planning and prioritizing future work, we value your feedback! Below are a few issues we would love feedback on:

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 – September 2024 Release appeared first on Python.

Categories: FLOSS Project Planets

Real Python: The Real Python Podcast – Episode #219: Astrophysics and Astronomy With Python &amp; PyCon Africa 2024

Fri, 2024-09-06 08:00

Are you interested in practicing your Python skills while learning how to solve astrophysics and astronomy problems? Christopher Trudeau is back on the show this week, bringing another batch of PyCoder's Weekly articles and projects.

[ 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

Matt Layman: Kamal On A Droplet - Building SaaS #201

Thu, 2024-09-05 20:00
In this episode, we continued working with the Kamal deploy tool. Last time, we build a demo image. With this session, we created a Digital Ocean Droplet (i.e., VM) and deployed to that. Along the journey, we learned a lot about how Kamal operates.
Categories: FLOSS Project Planets

Python Software Foundation: Pallets projects added to scope of PSF CVE Numbering Authority

Thu, 2024-09-05 04:55
Last year the Python Software Foundation was announced as a CVE Numbering Authority (CNA) to manage and assign CVE IDs for CPython and pip. Becoming a CVE Numbering Authority allows the PSF to provide expertise about Python in the CVE ecosystem, ensuring that users have accurate and up-to-date information about vulnerabilities affecting key projects.
Today, the PSF is expanding our CNA scope to also include Pallets projects, such as Flask, Jinja, Click, and Quart. For a complete list, see the Pallets organization on GitHub. Please report any security vulnerabilities for these projects following the Pallets security policy.
 This work is being done to learn how the PSF can better serve Python's large ecosystem of projects in the context of the CVE ecosystem. The PSF previously published a guide on how open source projects can become their own CVE Numbering Authorities. You can learn more about the CVE CNA program on the CVE website.

Pallets is a fiscal sponsoree of the Python Software Foundation. Fiscal sponsorship is a key plank of the PSF’s mission in supporting the Python community. The PSF supports 20 fiscal sponsorees including regional PyCons, Python Meetup and User Groups, and Python projects. Learn more about our Fiscal Sponsorees on our website and consider supporting the groups with a US-tax deductible donation.

Categories: FLOSS Project Planets

Python GUIs: Build a Translation Application Using Tkinter and OpenAI — Use ChatGPT to Translate Your Text from Python

Thu, 2024-09-05 02:00

Translation tools have existed for many years and are incredibly useful if you're learning a new language or wanting to read foreign websites. One of the most popular tools is Google Translate , but there is now another alternative: using OpenAI's ChatGPT tool to translate text.

In this tutorial, we'll build a desktop translator application to translate natural language using ChatGPT APIs. We'll be building the UI using the Tkinter library from the Python standard library:

Example translation of text via OpenAI

Table of Contents Installing the Required Packages

Our Translator uses the openai library to perform the actual translation via OpenAI's ChatGPT tool. Tkinter is already available in the standard library.

The first task will be to set up a Python virtual environment. Open the terminal, and run the following commands:

bat > mkdir translator > cd translator > python -m venv venv > .\venv\Scripts\activate > python -m pip install openai sh $ mkdir translator $ cd translator/ $ python -m venv venv $ source venv/bin/activate (venv) $ python -m pip install openai

Working through these instructions, first we create a root directory for the Translator app. Next we create and activate a Python virtual environment for the project. Finally, we install the openai package.

Next, create a file named translator.py in the root of your project. Also add a folder called images/ where you'll store the icons for the application. The folder structure should look like this:

python translator/ &boxv &boxvr&boxh&boxh images/ &boxv &boxvr&boxh&boxh arrow.png &boxv &boxur&boxh&boxh logo.png &boxv &boxur&boxh&boxh translator.py

The images for this project can be downloaded here.

The images/ folder contains the two icons that you'll use for the application. The translator.py is the app's source file.

Building the Window

Open the translator.py file with your favorite Python code editor. We'll start by creating our main window:

python import tkinter as tk class TranslatorApp(tk.Tk): def __init__(self): super().__init__() self.title("Language Translator") self.resizable(width=False, height=False) if __name__ == "__main__": app = TranslatorApp() app.mainloop()

This code imports Tkinter and then defines the application's main class, which we have called TranslatorApp. This class will hold the application's main window and allow us to run the main loop.

Importing tkinter under the alias tk is a common convention in Tkinter code.

Inside the class we define the __init__() method, which handles initialization of the class. In this method, we first call the initializer __init__() of the parent class, tk.Tk, to initialize the app's window. Then, we set the window's title using the title() method. To make the window unresizable, we use the resizable() method with width and height set to False.

At the bottom of the code, we have the if __name__ == "__main__" idiom to check whether the file is being run directly as an executable program. Inside the condition block we first create an instance of TranslatorApp and then run the application's main loop or event loop.

If you run this code, you'll get an empty Tkinter window on your desktop:

python $ python translator.py

The empty Tkinter window

Creating the GUI for the Translator App

Now that the main window is set up, let's start adding widgets to build the GUI. To do this, we'll create a method called setup_ui(), as shown below:

python import tkinter as tk class TranslatorApp(tk.Tk): def __init__(self): super().__init__() self.title("Language Translator") self.resizable(width=False, height=False) self.setup_ui() def setup_ui(self): frame = tk.Frame(self) frame.pack(padx=10, pady=10) if __name__ == "__main__": app = TranslatorApp() app.mainloop()

The setup_ui() method will define the application's GUI. In this method, we first create a frame widget using the tk.Frame class whose master argument is set to self (the application's main window). Next, we position the frame inside the main window using the pack() geometry manager, using padx and pady arguments to set some padding around the frame.

Finally, we add the call to self.setup_ui() to the __init__() method.

We'll continue to develop the UI by adding code to the setup_ui() method.

Net, we'll add the app's logo. In the setup_ui() method add the following code below the frame definition:

python import tkinter as tk class TranslatorApp(tk.Tk): def __init__(self): super().__init__() self.title("Language Translator") self.resizable(width=False, height=False) self.setup_ui() def setup_ui(self): frame = tk.Frame(self) frame.pack(padx=10, pady=10) self.logo = tk.PhotoImage(file="images/logo.png") tk.Label(frame, image=self.logo).grid(row=0, column=0, sticky="w") if __name__ == "__main__": app = TranslatorApp() app.mainloop()

This code loads the logo using the tk.PhotoImage class. To resize it, we use the subsample() method. Then, we add the logo to the frame using a tk.Label widget. The label takes the frame and the logo as arguments. Finally, to position the logo, we use the grid() geometry manager with appropriate values for the row, column, and sticky arguments.

The sticky argument determines which side of a cell the widget should align -- North (top), South (bottom), East (right) or West (left). Here we're aligning it on the Wiest or left of the cell with "w":

Tkinter window with the OpenAI logo in it

Getting a List of Languages

We need list of languages to shown in the dropdown. There are various lists available online. But since we're using OpenAI for the translations, why not use it to give us the list of languages too. Since this is just for testing purposes, lets grab the top 20 human languages (by first and second language speakers).

We can prompt ChatGPT with something like:

Give me a list of the top 20 human languages with the most first and second language speakers in Python list format

..and it will return the following list:

python languages = [ "English", "Mandarin Chinese", "Hindi", "Spanish", "French", "Standard Arabic", "Bengali", "Russian", "Portuguese", "Urdu" ]

I'm going to add Dutch to the list, because it's my second language. Feel free to add your own languages to the list.

Adding the Interface

Let's start adding some inputs to the UIs. First we'll create the language selection drop down boxes:

python import tkinter as tk import tkinter.ttk as ttk LANGUAGES = [ "English", "Mandarin Chinese", "Hindi", "Spanish", "French", "Standard Arabic", "Bengali", "Russian", "Portuguese", "Urdu", "Dutch", # Gekoloniseerd. ] DEFAULT_SOURCE = "English" DEFAULT_DEST = "Dutch" class TranslatorApp(tk.Tk): def __init__(self): super().__init__() self.title("Language Translator") self.resizable(width=False, height=False) self.setup_ui() def setup_ui(self): frame = tk.Frame(self) frame.pack(padx=10, pady=10) self.logo = tk.PhotoImage(file="images/logo.png") tk.Label(frame, image=self.logo).grid(row=0, column=0, sticky="w") # Source language combobox self.from_language = ttk.Combobox(frame, values=LANGUAGES) self.from_language.current(LANGUAGES.index(DEFAULT_SOURCE)) self.from_language.grid(row=1, column=0, sticky="we") # Arrow icon self.arrows = tk.PhotoImage(file="images/arrow.png").subsample(15, 15) tk.Label(frame, image=self.arrows).grid(row=1, column=1) # Destination language combobox self.to_language = ttk.Combobox(frame, values=LANGUAGES) self.to_language.current(LANGUAGES.index(DEFAULT_DEST)) self.to_language.grid(row=1, column=2, sticky="we") if __name__ == "__main__": app = TranslatorApp() app.mainloop()

We have added our language list as the constant LANGUAGES. We also define the default languages for when the application starts up, using constants DEFAULT_SOURCE and DEFAULT_DEST.

Next, we create two combo boxes to hold the list of source and destination languages. The combo boxes are created using the ttk.Combobox class. One to the left and another to the right. Between the combo boxes, we've also added an arrow icon loaded using the tk.PhotoImage class. Again, we've added the icon to the app's window using ttk.Label.

Both combo boxes take frame and values as arguments. The values argument populates the combo boxes with languages. To specify the default language, we use the current() method, looking up the position of our default languages in the languages list with .index().

To position the combo boxes inside the frame, we use the grid() geometry manager with the appropriate arguments. Run the application, and you will see the following window:

Source and destination languages

With the source and destination combo boxes in place, let's add three more widgets: two scrollable text widgets and a button. The scrollable text on the left will hold the source text, while the scrollable text on the right will hold the translated text. The button will allow us to run the actual translation.

Building the Input UI

Get back to the code editor and update the setup_ui() method as follows. Note that we also need to import the ScrollText class:

python import tkinter as tk import tkinter.ttk as ttk from tkinter.scrolledtext import ScrolledText LANGUAGES = [ "English", "Mandarin Chinese", "Hindi", "Spanish", "French", "Standard Arabic", "Bengali", "Russian", "Portuguese", "Urdu", "Dutch", ] DEFAULT_SOURCE = "English" DEFAULT_DEST = "Dutch" class TranslatorApp(tk.Tk): def __init__(self): super().__init__() self.title("Language Translator") self.resizable(width=False, height=False) self.setup_ui() def setup_ui(self): frame = tk.Frame(self) frame.pack(padx=10, pady=10) self.logo = tk.PhotoImage(file="images/logo.png").subsample(5, 5) tk.Label(frame, image=self.logo).grid(row=0, column=0, sticky="w") # Source language combobox languages = [lang.title() for lang in LANGUAGES.values()] self.from_language = ttk.Combobox(frame, values=languages) self.from_language.current(languages.index(DEFAULT_SOURCE)) self.from_language.grid(row=1, column=0, sticky="we") # Arrow icon self.arrows = tk.PhotoImage(file="images/arrow.png").subsample(15, 15) tk.Label(frame, image=self.arrows).grid(row=1, column=1) # Destination language combobox self.to_language = ttk.Combobox(frame, values=languages) self.to_language.current(languages.index(DEFAULT_DEST)) self.to_language.grid(row=1, column=2, sticky="we") # Source text self.from_text = ScrolledText( frame, font=("Dotum", 16), width=50, height=20, ) self.from_text.grid(row=2, column=0) # Translated text self.to_text = ScrolledText( frame, font=("Dotum", 16), width=50, height=20, state="disabled", ) self.to_text.grid(row=2, column=2) # Translate button self.translate_button = ttk.Button( frame, text="Translate", command=self.translate, ) self.translate_button.grid(row=3, column=0, columnspan=3, pady=10) def translate(self): pass if __name__ == "__main__": app = TranslatorApp() app.mainloop()

In the code snippet, we use the ScrolledText class to create the two scrolled text areas. Both text areas take frame, font, width, and height as arguments. The second text area also takes state as an additional argument. Setting state to "disabled" allows us to create a read-only text area.

Then, we use the ttk.Button class to create a button with frame, text, and command as arguments. The command argument allows us to bind the button's click event to the self.translate() method, which we will define in a moment. For now, we've added a placeholder.

To position all these widgets on the app's window, we use the grid() geometry manager. Now, the app will look something like the following:

Translator app's GUI

Our translation app's GUI is ready! Finally, we can start adding functionality to the application.

Getting an OpenAI API Key

You can use OpenAPI's APIs for free, with some limitations. To get an OpenAI API key you will need to create an account. Once you have created an account go ahead and get an API key.

Click "Create new secret key" in the top right hand corner to create a key. Give the key a name (it doesn't matter what you use) and then click "Create secret key". Copy the resulting key and keep it safe. You'll need it in the next step.

Implementing the Translation Functionality

We'll implement the language translation functionality in the translate() method. This gets the current text from the UI and then uses openai to perform the translation. We need a few more imports, and to create the OpenAI client instance at the top of the application:

python import tkinter as tk import tkinter.ttk as ttk from tkinter.messagebox import showerror from tkinter.scrolledtext import ScrolledText import httpcore from openai import OpenAI client = OpenAI( api_key="<YOUR API KEY HERE>" )

Here we've imported the showerror helper for displaying error boxes in our application. We've imported httpcore which we'll use to handle HTTP errors when accessing the API. Finally, we've added an import for the OpenAI class from openai. This is what handles the actual translation.

To use it, we create an instance of the class as OpenAI. Replace <YOUR API KEY HERE> with the API key you generated on OpenAI just now.

We'll continue by implementing the translate() method. Below we're just showing the function itself:

python class TranslatorApp(tk.Tk): # ... def translate(self): source_language = self.from_language.get() destination_language = self.to_language.get() text = self.from_text.get(1.0, tk.END).strip() try: completion = client.chat.completions.create( messages=[ {"role": "system", "content": "You are a language interpreter."}, { "role": "user", "content": ( f"Translate the following text from {source_language} " f"to {destination_language}, only reply with the text: " f"{text}" ), }, ], model="gpt-3.5-turbo", ) reply = completion.choices[0].message.content except httpcore.ConnectError: showerror( title="Error", message="Make sure you have an internet connection", ) return except Exception as e: showerror( title="Error", message=f"An unexpected error occurred: {e}", ) return self.to_text.config(state="normal") self.to_text.delete(1.0, tk.END) self.to_text.insert(tk.END, reply) self.to_text.config(state="disabled")

The translate() method handles the entire translation process. It starts by retrieving the source and destination languages from the corresponding combo boxes, and the input text from the box on the left.

If any of these are not defined, we use a showerror dialog to inform the user of the problem.

Once we have the source and destination language and some text to translate, we can perform the actual translation through ChatGPT. First, we give the language model a hint about what we want it to do -- interpret language:

python {"role": "system", "content": "You are a language interpreter."},

Next we build the message we want it to respond to. We ask it to translate the provided text from the source to destination language, and to respond with only the translated text. If we don't specify this, we'll get some additional description or context.

You might want to experiment with asking for the text and context separately, as that is often helpful when learning languages.

python { "role": "user", "content": ( f"Translate the following text from {source_language} " f"to {destination_language}, only reply with the text: " f"{text}" ), },

The created completion is submitted to the API and we can retrieve the resulting text from the object:

python reply = completion.choices[0].message.content

If the call to translate() finds a connection error, then we tell the user to check their internet connection. To handle any other exceptions, we catch the generic Exception class and display an error message with the exception details.

If the translation is successful, then we enable the destination scrolled area, display the translated text, and disable the area again so it remains read-only.

The complete final code is shown below:

python import tkinter as tk import tkinter.ttk as ttk from tkinter.messagebox import showerror from tkinter.scrolledtext import ScrolledText import httpcore from openai import OpenAI client = OpenAI( api_key="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" ) LANGUAGES = [ "English", "Mandarin Chinese", "Hindi", "Spanish", "French", "Standard Arabic", "Bengali", "Russian", "Portuguese", "Urdu", "Dutch", ] DEFAULT_SOURCE = "English" DEFAULT_DEST = "Dutch" class TranslatorApp(tk.Tk): def __init__(self): super().__init__() self.title("Language Translator") self.resizable(width=False, height=False) self.setup_ui() def setup_ui(self): frame = tk.Frame(self) frame.pack(padx=10, pady=10) self.logo = tk.PhotoImage(file="images/logo.png") tk.Label(frame, image=self.logo).grid(row=0, column=0, sticky="w") # Source language combobox self.from_language = ttk.Combobox(frame, values=LANGUAGES) self.from_language.current(LANGUAGES.index(DEFAULT_SOURCE)) self.from_language.grid(row=1, column=0, sticky="we") # Arrow icon self.arrows = tk.PhotoImage(file="images/arrow.png").subsample(15, 15) tk.Label(frame, image=self.arrows).grid(row=1, column=1) # Destination language combobox self.to_language = ttk.Combobox(frame, values=LANGUAGES) self.to_language.current(LANGUAGES.index(DEFAULT_DEST)) self.to_language.grid(row=1, column=2, sticky="we") # Source text self.from_text = ScrolledText( frame, font=("Dotum", 16), width=50, height=20, ) self.from_text.grid(row=2, column=0) # Translated text self.to_text = ScrolledText( frame, font=("Dotum", 16), width=50, height=20, state="disabled", ) self.to_text.grid(row=2, column=2) # Translate button self.translate_button = ttk.Button( frame, text="Translate", command=self.translate, ) self.translate_button.grid(row=3, column=0, columnspan=3, pady=10) def translate(self): source_language = self.from_language.get() destination_language = self.to_language.get() text = self.from_text.get(1.0, tk.END).strip() try: completion = client.chat.completions.create( messages=[ {"role": "system", "content": "You are a language interpreter."}, { "role": "user", "content": ( f"Translate the following text from {source_language} " f"to {destination_language}, only reply with the text: " f"{text}" ), }, ], model="gpt-3.5-turbo", ) reply = completion.choices[0].message.content except httpcore.ConnectError: showerror( title="Error", message="Make sure you have an internet connection", ) return except Exception as e: showerror( title="Error", message=f"An unexpected error occurred: {e}", ) return self.to_text.config(state="normal") self.to_text.delete(1.0, tk.END) self.to_text.insert(tk.END, reply) self.to_text.config(state="disabled") if __name__ == "__main__": app = TranslatorApp() app.mainloop()

The finished app is shown below:

The completed Translator app

Conclusion

In this tutorial we built a Translator application using the Tkinter GUI library from the Python standard library. We worked step by step through building the UI using a grid layout, and then implemented the language translation functionality with openai & ChatGPT.

Try and take what you've learnt in this tutorial & applying it to your own projects!

Categories: FLOSS Project Planets

Quansight Labs Blog: Announcing Scientific Python Accessibility Events

Wed, 2024-09-04 20:00
I am happy to announce two upcoming public events focused on helping the scientific Python ecosystem develop their accessibility skills before the new year.
Categories: FLOSS Project Planets

Stefanie Molin: How to Create a Pre-Commit Hook

Wed, 2024-09-04 10:55
Pre-commit hooks are a great way to help maintain code quality. However, some of your code quality standards may be specific to your project, and therefore, not covered by existing code linting and formatting tools. In this article, I will show you how to incorporate custom checks into your `pre-commit` setup.
Categories: FLOSS Project Planets

Real Python: Lists vs Tuples in Python

Wed, 2024-09-04 10:00

In Python, lists and tuples are versatile and useful data types that allow you to store data in a sequence. You’ll find them in virtually every nontrivial Python program. Learning about them is a core skill for you as a Python developer.

In this tutorial, you’ll:

  • Get to know lists and tuples
  • Explore the core characteristics of lists and tuples
  • Learn how to define and manipulate lists and tuples
  • Decide when to use lists or tuples in your code

To get the most out of this tutorial, you should know the basics of Python programming, including how to define variables.

Get Your Code: Click here to download the free sample code that shows you how to work with lists and tuples in Python.

Take the Quiz: Test your knowledge with our interactive “Lists vs Tuples in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Lists vs Tuples in Python

Challenge yourself with this quiz to evaluate and deepen your understanding of Python lists and tuples. You'll explore key concepts, such as how to create, access, and manipulate these data types, while also learning best practices for using them efficiently in your code.

Getting Started With Python Lists and Tuples

In Python, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. To define a list, you typically enclose a comma-separated sequence of objects in square brackets ([]), as shown below:

Python >>> colors = ["red", "green", "blue", "yellow"] >>> colors ['red', 'green', 'blue', 'yellow'] Copied!

In this code snippet, you define a list of colors using string objects separated by commas and enclose them in square brackets.

Similarly, tuples are also collections of arbitrary objects. To define a tuple, you’ll enclose a comma-separated sequence of objects in parentheses (()), as shown below:

Python >>> person = ("Jane Doe", 25, "Python Developer", "Canada") >>> person ('Jane Doe', 25, 'Python Developer', 'Canada') Copied!

In this example, you define a tuple with data for a given person, including their name, age, job, and base country.

Up to this point, it may seem that lists and tuples are mostly the same. However, there’s an important difference:

Feature List Tuple Is an ordered sequence ✅ ✅ Can contain arbitrary objects ✅ ✅ Can be indexed and sliced ✅ ✅ Can be nested ✅ ✅ Is mutable ✅ ❌

Both lists and tuples are sequence data types, which means they can contain objects arranged in order. You can access those objects using an integer index that represents their position in the sequence.

Even though both data types can contain arbitrary and heterogeneous objects, you’ll commonly use lists to store homogeneous objects and tuples to store heterogeneous objects.

Note: In this tutorial, you’ll see the terms homogeneous and heterogeneous used to express the following ideas:

  • Homogeneous: Objects of the same data type or the same semantic meaning, like a series of animals, fruits, colors, and so on.
  • Heterogeneous: Objects of different data types or different semantic meanings, like the attributes of a car: model, color, make, year, fuel type, and so on.

You can perform indexing and slicing operations on both lists and tuples. You can also have nested lists and nested tuples or a combination of them, like a list of tuples.

The most notable difference between lists and tuples is that lists are mutable, while tuples are immutable. This feature distinguishes them and drives their specific use cases.

Essentially, a list doesn’t have a fixed length since it’s immutable. Therefore, it’s natural to use homogeneous elements to have some structure in the list. A tuple, on the other hand, has a fixed length so the position of elements can have meaning, supporting heterogeneous data.

Creating Lists in Python

In many situations, you’ll define a list object using a literal. A list literal is a comma-separated sequence of objects enclosed in square brackets:

Python >>> countries = ["United States", "Canada", "Poland", "Germany", "Austria"] >>> countries ['United States', 'Canada', 'Poland', 'Germany', 'Austria'] Copied!

In this example, you create a list of countries represented by string objects. Because lists are ordered sequences, the values retain the insertion order.

Read the full article at https://realpython.com/python-lists-tuples/ »

[ 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

Real Python: Quiz: Lists vs Tuples in Python

Wed, 2024-09-04 08:00

Challenge yourself with this quiz to evaluate and deepen your understanding of Python lists and tuples. You’ll explore key concepts, such as how to create and manipulate these data types, while also learning best practices for using them efficiently in your code.

You can take this quiz after reading the Lists vs Tuples in Python tutorial.

[ 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

Hynek Schlawack: Production-ready Python Docker Containers with uv

Wed, 2024-09-04 06:00

Starting with 0.3.0, Astral’s uv brought many great features, including support for cross-platform lock files uv.lock. Together with subsequent fixes, it has become Python’s finest workflow tool for my (non-scientific) use cases. Here’s how I build production-ready containers, as fast as possible.

Categories: FLOSS Project Planets

Talk Python to Me: #476: Unified Python packaging with uv

Wed, 2024-09-04 04:00
A couple of weeks ago, Charlie Marsh and the folks at Astral made another big splash with a major release of uv called "uv: Unified Python packaging" which has many far reaching features. We had to have Charlie on the show to give us the inside look into this development. Let's get to it.<br/> <br/> <strong>Episode sponsors</strong><br/> <br/> <a href='https://talkpython.fm/posit'>Posit</a><br> <a href='https://talkpython.fm/training'>Talk Python Courses</a><br/> <br/> <strong>Links from the show</strong><br/> <br/> <div><b>Charlie Marsh on Twitter</b>: <a href="https://twitter.com/charliermarsh?featured_on=talkpython" target="_blank" >@charliermarsh</a><br/> <b>Charlie Marsh on Mastodon</b>: <a href="https://hachyderm.io/@charliermarsh?featured_on=talkpython" target="_blank" >@charliermarsh</a><br/> <br/> <b>uv: Unified Python packaging</b>: <a href="https://astral.sh/blog/uv-unified-python-packaging?featured_on=talkpython" target="_blank" >astral.sh</a><br/> <b>Python executable management</b>: <a href="https://docs.astral.sh/uv/concepts/python-versions/?featured_on=talkpython" target="_blank" >astral.sh</a><br/> <b>Projects</b>: <a href="https://docs.astral.sh/uv/concepts/projects/?featured_on=talkpython" target="_blank" >astral.sh</a><br/> <b>Tools</b>: <a href="https://docs.astral.sh/uv/concepts/tools/?featured_on=talkpython" target="_blank" >astral.sh</a><br/> <b>Scripts</b>: <a href="https://docs.astral.sh/uv/guides/scripts/?featured_on=talkpython" target="_blank" >astral.sh</a><br/> <b>Rye and uv: August is Harvest Season for Python Packaging</b>: <a href="https://lucumr.pocoo.org/2024/8/21/harvest-season/?featured_on=talkpython" target="_blank" >lucumr.pocoo.org</a><br/> <b>Python Build Standalone releases</b>: <a href="https://github.com/indygreg/python-build-standalone/releases?featured_on=talkpython" target="_blank" >github.com</a><br/> <b>Rules</b>: <a href="https://docs.astral.sh/ruff/rules/?featured_on=talkpython" target="_blank" >astral.sh</a><br/> <b>Watch this episode on YouTube</b>: <a href="https://www.youtube.com/watch?v=oj8yk0Y-Ky0" target="_blank" >youtube.com</a><br/> <b>Episode transcripts</b>: <a href="https://talkpython.fm/episodes/transcript/476/unified-python-packaging-with-uv" 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>
Categories: FLOSS Project Planets

PyCoder’s Weekly: Issue #645 (Sept. 3, 2024)

Tue, 2024-09-03 15:30

#645 – SEPTEMBER 3, 2024
View in Browser »

Using Astropy for Astronomy With Python

This course covers two problems from introductory astronomy to help you play with some Python libraries. You’ll use NumPy, Matplotlib, and pandas to find planet conjunctions, and graph the best viewing times for a star.
REAL PYTHON course

Python Language Summit 2024

Talk Python to Me interviews Seth Michael Larson and they talk about this year’s Python Language Summit. Learn all about what happened at the closed door session for core developers inside PyCon.
KENNEDY & LARSON podcast

Instant PEP 8 Compliance Checks & Fixes With Top AI Code Reviewer

With CodeRabbit, solve your indentation issues and security concerns. CodeRabbit doesn’t just point out issues; it suggests fixes and explains the reasoning behind the suggestion. Elevate code quality with AI-powered, context-aware reviews and 1-click fixes. Sign up for free today →
CODERABBIT sponsor

Layman’s Guide to Python Built-in Functions

This is a plain language guide to every built-in function in Python, paired with a simple example that shows each function in action.
MATT LAYMAN

DjangoCon Europe 2026 Call for Organizers

DJANGO SOFTWARE FOUNDATION

PyPy v7.3.17 Release

PYPY.ORG

Quiz: Python Strings and Character Data

REAL PYTHON

Quiz: Python String Formatting

REAL PYTHON

Articles & Tutorials Sorting Dictionaries in Python: Keys, Values, and More

In this video course, you’ll learn how to sort Python dictionaries. By the end, you’ll be able to sort by key, value, or even nested attributes. But you won’t stop there—you’ll also measure the performance of variations when sorting and compare different key-value data structures.
REAL PYTHON course

Understanding the Template Method Pattern in Python

The Template Method Pattern is when a base class is used to implement a series of steps, and subclasses can override one or more of those steps to customize the process. This article shows an example usage in Python and why you might want to implement it.
LANCE GOYKE

Accelerate Edge Devices With High-Performance AI Power

Experience the power of Edge AI—delivering lightning-fast, real-time processing where it matters. Optimize your applications with low latency, high efficiency, and unparalleled accuracy. Push performance beyond limits with Intel’s OpenVINO toolkit.
INTEL CORPORATION sponsor

Asyncio gather() Limit Concurrency

The asyncio.gather() function allows you to run multiple co-routines concurrently. There are times when you want to control just how much concurrency you have though and this post shows you how to use a semaphore to do just that.
JASON BROWNLEE

Adventures Building a Spreadsheet Engine in Python

Spreadsheets are a fascinating tool: you can both store and structure data, and include formulas that run computations on the contents of a sheet. James has written a spreadsheet engine, and this post talks about how it is done.
JAMES G

What’s New in pip 24.2

In version 24.2, pip learns to use system certificates by default, receives a handful of optimizations, and deprecates legacy (setup.py develop) editable installations. This article covers the changes and why they’ve been made.
RICHARD SI

CPython Compiler Hardening

Nate has been working on the CPython compiler, applying memory hardening guidelines recommended by OpenSSF’s Memory Safety Special Interest Group. This blog post talks about what was applied and how it should improve CPython.
NATE OHLSON

A Comparison of Providers for Python Serverless Functions

This is a comparison chart of the most common host providers that support Python serverless functions. It compares what features are supported, pricing, runtime limits, and more.
HAROLD MARTIN

There Can’t Be Only One

A weird historical first in baseball recently reminded James about how often as programmers we map our data assuming a one-to-one relationship, and how often that’s a bad choice.
JAMES BENNETT

Safety & Security Engineer: First Year in Review

It has been a year since Mike joined the PSF as the Safety & Security Engineer for PyPI. This blog post talks about all the things he’s been involved with.
MIKE FIELDER

Python Developers Survey 2023 Results

Official Python Developers Survey 2023 Results by Python Software Foundation and JetBrains: more than 25k responses from almost 200 countries.
JETBRAINS.COM

Lesser Known Parts of Python Standard Library

This article covers some of the lesser used parts of the Python standard library, including Deque, defaultdict, UserDict, and more.
TRICKSTER DEV

Projects & Code AlgoTree: A Package for Working With Tree Structures

PYPI.ORG • Shared by Alex Towell

anacondacode: Execute Python Directly From Excel

PYPI.ORG

pare: Deploy Python Lambdas Alongside Your Web App

GITHUB.COM/GAUGE-SH

django-admin-action-forms: Forms for Django Admin

GITHUB.COM/MICHALPOKUSA

PromptMage Simplifies Managing LLM Workflows

PROMPTMAGE.IO • Shared by Tobias Sterbak

Events EARL 2024

September 4 to September 6, 2024
DATACOVE.CO.UK

Weekly Real Python Office Hours Q&A (Virtual)

September 4, 2024
REALPYTHON.COM

PyCon Estonia 2024

September 5 to September 7, 2024
PYCON.EE

Canberra Python Meetup

September 5, 2024
MEETUP.COM

Sydney Python User Group (SyPy)

September 5, 2024
SYPY.ORG

PyDelhi User Group Meetup

September 7, 2024
MEETUP.COM

Happy Pythoning!
This was PyCoder’s Weekly Issue #645.
View in Browser »

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

Categories: FLOSS Project Planets

Mike Driscoll: ANN: JupyterLab 101 Kickstarter

Tue, 2024-09-03 10:08

My latest Python book is now available for pre-order on Kickstarter.

JupyterLab 101 mockup

JupyterLab, the latest iteration of the Jupyter Notebook, is a versatile tool for sharing code in an easily understandable format.

Hundreds of thousands of people around the world use Jupyter Notebooks or variations of the Notebook architecture for any or all of the following:

  • teaching
  • presentations
  • learning a computer language
  • numerical simulations
  • statistical modeling
  • data visualization
  • machine learning
  • and much more!

Jupyter Notebooks can be emailed, put on GitHub, or run online. You may also add HTML, images, Markdown, videos, LaTeX, and custom MIME types to your Notebooks. Finally, Jupyter Notebooks support big data integration.

JupyterLab 101 will get you up to speed on the newest user interface for Jupyter Notebooks and the other tools that JupyterLab supports. You now have a tabbed interface that you can use to edit multiple Notebooks, open terminals in your browser, create a Python REPL, and more. JupyterLab also includes a debugger utility to help you figure out your coding issues.

Rest assured, JupyterLab supports all the same programming languages as Jupyter Notebook. The main difference lies in the user interface, which this guide will help you navigate effectively and efficiently.

After reading JupyterLab 101, you will be an expert in JupyterLab and produce quality Notebooks quickly!

What You’ll Learn

In this book, you will learn how about the following:

  • Installation and setup of JupyterLab
  • The JupyterLab user interface
  • Creating a Notebook
  • Markdown in Notebooks
  • Menus in JupyterLab
  • Launching Other Applications (console, terminal, text files, etc)
  • Distributing and Exporting Notebooks
  • Debugging in JupyterLab
  • Testing your notebooks
Rewards to Choose From

As a backer of this Kickstarter, you have some choices to make. You can receive one or more of the following, depending on which level you choose when backing the project:

  • An early copy of JupyterLab 101 + all updates including the final version (ALL BACKERS)
  • A signed paperback copy (If you choose the appropriate perk)
  • Get all by Python courses hosted on Teach Me Python or another site  (If you choose the appropriate perk)
  • T-shirt with the book cover  (If you choose the appropriate perk)

Get the book on Kickstarter today!

The post ANN: JupyterLab 101 Kickstarter appeared first on Mouse Vs Python.

Categories: FLOSS Project Planets

Real Python: Using Pydantic to Simplify Python Data Validation

Tue, 2024-09-03 10:00

Pydantic is a powerful data validation and settings management library for Python, engineered to enhance the robustness and reliability of your codebase. From basic tasks, such as checking whether a variable is an integer, to more complex tasks, like ensuring highly-nested dictionary keys and values have the correct data types, Pydantic can handle just about any data validation scenario with minimal boilerplate code.

In this video course, you’ll learn how to:

  • Work with data schemas with Pydantic’s BaseModel
  • Write custom validators for complex use cases
  • Validate function arguments with Pydantic’s @validate_call
  • Manage settings and configure applications with pydantic-settings

[ 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

Django Weblog: Django security releases issued: 5.1.1, 5.0.9, and 4.2.16

Tue, 2024-09-03 07:00

In accordance with our security release policy, the Django team is issuing releases for Django 5.1.1, Django 5.0.9, and Django 4.2.16. These releases address the security issues detailed below. We encourage all users of Django to upgrade as soon as possible.

CVE-2024-45230: Potential denial-of-service vulnerability in django.utils.html.urlize()

urlize and urlizetrunc were subject to a potential denial-of-service attack via very large inputs with a specific sequence of characters.

Thanks to MProgrammer for the report.

This issue has severity "moderate" according to the Django security policy.

CVE-2024-45231: Potential user email enumeration via response status on password reset

Due to unhandled email sending failures, the django.contrib.auth.forms.PasswordResetForm class allowed remote attackers to enumerate user emails by issuing password reset requests and observing the outcomes.

To mitigate this risk, exceptions occurring during password reset email sending are now handled and logged using the django.contrib.auth logger.

Thanks to Thibaut Spriet for the report.

This issue has severity "low" according to the Django security policy.

Affected supported versions
  • Django main branch
  • Django 5.1
  • Django 5.0
  • Django 4.2
Resolution

Patches to resolve the issue have been applied to Django's main, 5.1, 5.0, and 4.2 branches. The patches may be obtained from the following changesets.

CVE-2024-45230: Potential denial-of-service vulnerability in django.utils.html.urlize() CVE-2024-45231: Potential user email enumeration via response status on password reset The following releases have been issued

The PGP key ID used for this release is Natalia Bidart: 2EE82A8D9470983E

General notes regarding security reporting

As always, we ask that potential security issues be reported via private email to security@djangoproject.com, and not via Django's Trac instance, nor via the Django Forum, nor via the django-developers list. Please see our security policies for further information.

Categories: FLOSS Project Planets

Python Bytes: #399 C will watch you in silence

Tue, 2024-09-03 04:00
<strong>Topics covered in this episode:</strong><br> <ul> <li><strong><a href="https://hynek.me/articles/docker-virtualenv/?featured_on=pythonbytes">Why I Still Use Python Virtual Environments in Docker</a></strong></li> <li><a href="https://lp.jetbrains.com/python-developers-survey-2023/?featured_on=pythonbytes"><strong>Python Developer Survey Results</strong></a></li> <li><strong><a href="https://www.anaconda.com/blog/introducing-anaconda-code-add-in-for-microsoft-excel?featured_on=pythonbytes">Anaconda Code add-in for Microsoft Excel</a></strong></li> <li><a href="https://davidism.com/disabling-scheduled-dependency-updates/?featured_on=pythonbytes"><strong>Disabling Scheduled Dependency Updates</strong></a></li> <li><strong>Extras</strong></li> <li><strong>Joke</strong></li> </ul><a href='https://www.youtube.com/watch?v=dpAPT-T5m2g' style='font-weight: bold;'data-umami-event="Livestream-Past" data-umami-event-episode="399">Watch on YouTube</a><br> <p><strong>About the show</strong></p> <p>Sponsored by us! Support our work through</p> <ul> <li>Our <a href="https://training.talkpython.fm/?featured_on=pythonbytes"><strong>courses at Talk Python Training</strong></a></li> <li><a href="https://courses.pythontest.com/?featured_on=pythonbytes"><strong>Hello, pytest! Course</strong></a></li> <li><a href="https://www.patreon.com/pythonbytes"><strong>Patreon Supporters</strong></a></li> </ul> <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>Michael #1:</strong> <a href="https://hynek.me/articles/docker-virtualenv/?featured_on=pythonbytes">Why I Still Use Python Virtual Environments in Docker</a></p> <ul> <li>by Hynek Schlawack</li> <li>I was going to cover <a href="https://hynek.me/articles/docker-uv/?featured_on=pythonbytes">Production-ready Docker Containers with uv</a> but decided to take this diversion instead.</li> <li>Spend a lot of time thinking about the secondary effects of what you do.</li> <li>venvs are well known and well documented. Let’s use them.</li> </ul> <p><strong>Brian #2:</strong> <a href="https://lp.jetbrains.com/python-developers-survey-2023/?featured_on=pythonbytes"><strong>Python Developer Survey Results</strong></a></p> <ul> <li>“… official Python Developers Survey, conducted as a collaborative effort between the Python Software Foundation and JetBrains.”</li> <li>Python w/ Rust rising, but still only 7%</li> <li>““The drop in HTML/CSS/JS might show that data science is increasing its share of Python.” - Paul Everitt</li> <li>37% contribute to open source. Awesome.</li> <li>Favorite Resources: Podcasts <ul> <li>Lots of familiar faces there. Awesome. <ul> <li>Perhaps I shouldn’t have decided to move “Python Test” back to <a href="https://testandcode.com?featured_on=pythonbytes">Test &amp; Code</a></li> </ul></li> </ul></li> <li>Usage <ul> <li>“Data analysis” down, but I think that’s because “data engineering” is added.</li> <li>Data, Web dev, ML, devops, academic, </li> <li>Testing is down <img src="https://paper.dropboxstatic.com/static/img/ace/emoji/1f61e.png?version=8.0.0" alt="disappointed face" /> 23%</li> </ul></li> <li>Python Versions <ul> <li>Still some 2 out there</li> <li>Most folks on 3.10-3.12</li> </ul></li> <li>Install from: mostly python.org</li> <li>Frameworks <ul> <li>web: Flask, Django, Requests, FastAPI …</li> <li>testing: pytest, unittest, mock, doctest, tox, hypothesis, nose (2% might be the Python 2 people)</li> </ul></li> <li>Data science <ul> <li>77% use pandas, 72% NumPy</li> </ul></li> <li>OS: Windows still at 55% </li> <li>Packaging: <ul> <li>venv up to 55%</li> <li>I imaging uv will be on the list next year</li> <li>requirements.txt 63%, pyproject.toml 32%</li> </ul></li> <li>virtual env in containers? 47% say no</li> </ul> <p><strong>Michael #3:</strong> <a href="https://www.anaconda.com/blog/introducing-anaconda-code-add-in-for-microsoft-excel?featured_on=pythonbytes">Anaconda Code add-in for Microsoft Excel</a></p> <ul> <li>Run their Python-powered projects in Excel locally with the Anaconda Code add-in</li> <li>Powered by PyScript, an Anaconda supported open source project that runs Python locally without install and setup</li> <li>Features <ul> <li>Cells Run Independently</li> <li>Range to Multiple Types</li> <li>init.py file is static and cannot be edited, with Anaconda Code, users have the ability to access and edit imports and definitions, allowing you to write top-level functions and classes and reuse them wherever you need. </li> <li>A Customizable Environment </li> </ul></li> </ul> <p><strong>Brian #4:</strong> <a href="https://davidism.com/disabling-scheduled-dependency-updates/?featured_on=pythonbytes"><strong>Disabling Scheduled Dependency Updates</strong></a></p> <ul> <li>David Lord</li> <li>Interesting discussion of as they happen or batching of upsates to dependencies</li> <li>dependencies come in <ul> <li>requirements files</li> <li>GH Actions in CI workflows</li> <li>pre-commit hooks</li> </ul></li> <li>David was seeing 60 PRs per month when set up on monthly updates (3 ecosystems * 20 projects)</li> <li>new tool for updating GH actions: <a href="https://gha-update.readthedocs.io/en/latest/?featured_on=pythonbytes">gha-update</a>, allows for local updating of GH dependencies</li> <li>New process <ul> <li>Run pip-compile, gha-update, and pre-commit locally.</li> <li>Update a project’s dependencies when actively working on the project, not just whenever a dependency updates.</li> <li>Note that this works fine for dev dependencies, less so for security updates from run time dependencies. But for libraries, runtime dependencies are usually not pinned.</li> </ul></li> </ul> <p><strong>Extras</strong> </p> <p>Brian:</p> <ul> <li><a href="https://testandcode.com?featured_on=pythonbytes">Test &amp; Code</a> coming back this week</li> </ul> <p>Michael:</p> <ul> <li><a href="https://www.codeinacastle.com/python-zero-to-hero-2024?featured_on=pythonbytes">Code in a Castle event</a></li> <li><a href="https://github.com/basnijholt/unidep/pull/191#issuecomment-2322392833">Python Bytes badge spotting</a></li> <li><a href="https://news.ycombinator.com/item?id=41385546&featured_on=pythonbytes">Guido’s post removed for moderation</a></li> </ul> <p><strong>Joke:</strong> <a href="https://devhumor.com/media/c-will-watch-in-silence?featured_on=pythonbytes">C will watch in silence</a></p>
Categories: FLOSS Project Planets

Pages