Michael Driscoll's Blog, page 6
April 17, 2024
Announcing The Python Logging Book & Course Kickstarter
What does every new developer do when they are first learning to program? They print out strings to their terminal. It’s how we learn! But printing out to the terminal isn’t what you do with most professional applications.
Support on KickstarterIn those cases, you log into files. Sometimes, you log into multiple locations at once. These logs may serve as an audit trail for compliance purposes or help the engineers debug what went wrong.
Python Logging teaches you how to log in the Python programming language. Python is one of the most popular programming languages in the world. Python comes with a logging module that makes logging easy.
What You’ll LearnIn this book, you will learn how about the following:
Logger objectsLog levelsLog handlersFormatting your logsLog configurationLogging decoratorsRotating logsLogging and concurrencyand more!Book formatsThe finished book will be made available in the following formats:
paperback (at the appropriate reward level)PDFepubThe paperback is a 6″ x 9″ book and is approximately 150 pages long.
You can support the book by clicking the button below:
Support on KickstarterThe post Announcing The Python Logging Book & Course Kickstarter appeared first on Mouse Vs Python.
April 9, 2024
Anaconda Partners with Teradata for AI with Python packages in the Cloud
Anaconda has announced a new partnership with Teradata to bring Python and R packages to Teradata VantageCloud through the Anaconda Repository.
But what does that mean? This new partnership allows engineers to:
Rapidly deploy and operationalize AI/ML developed using open-source Python and R packages.Unlock innovation and the full potential of data at scale with a wide variety of Python and R functionality on VantageCloud Lake.Flexibly use packages and versions of their choice for large-scale data science, AI/ML and generative AI use-cases.Securely work with Python/R models into VantageCloud Lake with no intellectual property (IP) leakage.Teradata VantageCloud Lake customers can download Python and R packages from the Anaconda Repository at no additional cost. Python packages are available immediately, and R packages will be released before the end of the year.
For more information about Teradata ClearScape Analytics, please visit Teradata.com.
Learn more about partnering with Anaconda here.
The post Anaconda Partners with Teradata for AI with Python packages in the Cloud appeared first on Mouse Vs Python.
March 14, 2024
Python 3.13 Allows Disabling of the GIL + subinterpreters
Python 3.13 adds the ability to remove the Global Interpreter Lock (GIL) per PEP 703. Just this past week, a PR was merged in that allows the disabling of the GIL using a command line flag or an environment variable in free-threaded builds. Note that Python must be built using the Py_GIL_DISABLED flag for this to work.
What is the GIL?The Global Interpreter Lock makes threading easier in Python and prevents race conditions. It also makes running multiple threads per CPU core impossible. However, you can use the multiprocessing module to at least give you the ability to better utilize the cores on your CPU.
Removing the GILRemoving the GIL will likely make Python buggy initially, so they are making the GIL-less version a build flag. That means that the GIL will still be on by default in Python 3.13 while they test the GIL-less version and find all the bugs the change causes. Hopefully, by 3.14 or so, they will know all the bugs and have them fixed to some degree or another.
Subinterpreters Are ComingA related enhancement are subinterpreters, which Eric Snow has worked on for quite some time. PEP 554 and PEP 734 cover what subinterpreters are and how they are being exposed so you can use them.
Here’s the abstract from PEP 734 to give you an idea of what they are:
This PEP proposes to add a new module, interpreters, to support inspecting, creating, and running code in multiple interpreters in the current process. This includes Interpreter objects that represent the underlying interpreters. The module will also provide a basic Queue class for communication between interpreters. Finally, we will add a new concurrent.futures.InterpreterPoolExecutor based on the interpreters module.
Both of these enhancements have lots of potential for making Python code faster, more efficient, or both. Peter Sobot announced he tried out the GIL removal flag for the pedalboard package and got a 17x speed up for certain processes.
The post Python 3.13 Allows Disabling of the GIL + subinterpreters appeared first on Mouse Vs Python.
March 13, 2024
NEW COURSE: Python 101 Video Course on Udemy and TutorialsPoint
I recently put my Python 101 Video Course up on Udemy and TutorialsPoint.
There are one thousand free copies of the course available on Udemy by using the following link:
https://www.udemy.com/course/python-101-c/?couponCode=A9CBEA3F6A1790FA40FFIf you prefer TutorialsPoint, you can get a free copy here:
https://www.tutorialspoint.com/python-101-with-mike-driscoll/index.aspUse coupon code: py101The Python 101 video course is also available on TeachMePython and my Gumroad store.
I am slowly adding quizzes to the Udemy version of the course and plan to add the same or similar quizzes on TeachMePython. Unfortunately, TutorialsPoint doesn’t support quizzes in the same way as they use a video quiz format, so that site won’t have any quizzes.
The post NEW COURSE: Python 101 Video Course on Udemy and TutorialsPoint appeared first on Mouse Vs Python.
February 27, 2024
uv – Python’s Fastest Package Installer and Resolver
There’s a new Python package installer out now and it’s called uv. The uv package installer and resolver is made by Astral. Uv is written in Rust instead of Python and is super fast! Astral is best known for Python’s fastest formatter, Ruff. The uv package is meant to be a drop-in replacement for pip and pip-tools. According to Astral, “uv is 8-10x faster than pip and pip-tools without caching, and 80-115x faster when running with a warm cache (e.g., recreating a virtual environment or updating a dependency)”.
Astral is also taking over the development of Rye, an experimental Python packaging tool from Armin Ronacher. From the sounds of Astral’s announcement, Rye and uv will become one tool as the two projects have a shared vision for Python packaging.
Installing uvYou can install uv using Curl:
curl -LsSf https://astral.sh/uv/install.sh | shOr you can use pip:
pip install uvNow that you have uv installed, you can start installing packages!
Using uvLet’s try running uv in your terminal:
c:\code> uvUsage: uv.exe [OPTIONS]
Commands:
pip Resolve and install Python packages
venv Create a virtual environment
cache Manage the cache
help Print this message or the help of the given subcommand(s)
Options:
-q, --quiet Do not print any output
-v, --verbose Use verbose output
--color Control colors in output [default: auto] [possible values: auto, always, never]
-n, --no-cache Avoid reading from or writing to the cache [env: UV_NO_CACHE=]
--cache-dir Path to the cache directory [env: UV_CACHE_DIR=]
-h, --help Print help (see more with '--help')
-V, --version Print version
You’ll need to create and activate a Python virtual environment to install packages with uv.
Here’s an example:
C:\code> uv venv testUsing Python 3.11.5 interpreter at C:\Users\wheifrd\AppData\Local\Programs\Python\Python311\python.exe
Creating virtualenv at: test
Activate with: test\Scripts\activate
C:\code> .\test\Scripts\activate
(test) C:\books>
Now you’re ready to install a Python package. You can use numpy for a test run:
(test) C:\books> uv pip install numpyResolved 1 package in 615ms
Downloaded 1 package in 2.81s
Installed 1 package in 332ms
+ numpy==1.26.4
As you might expect, you can also use uv to install:
a list of space-delimited packagesa requirements.txt filea pyproject.toml fileIf you need to generate a locked requirements.txt file, you can run uv pip compile.
Wrapping UpAstral hopes to create a “Cargo for Python” with the release of uv. While it’s still early, this project is well worth watching as the Rust package itself is amazingly fast and useful even though it’s only been out for about a year. You can read more about uv in Astral’s blog post.
The post uv – Python’s Fastest Package Installer and Resolver appeared first on Mouse Vs Python.
February 20, 2024
NEW COURSE: Automating Excel with Python on Udemy
In Automating Excel with Python: Processing Spreadsheets with OpenPyXL, you will learn how to use Python to create, edit, or read Microsoft Excel documents using OpenPyXL. This course is based on the book, Automating Excel with Python by Michael Driscoll.
Python is a versatile programming language. You can use Python to read, write and edit Microsoft Excel documents. You can use several Python packages, but this course will focus on OpenPyXL.
The OpenPyXL package allows you to work with Microsoft Excel files on Windows, Mac, and Linux, even if Excel isn’t installed.
In this course, you will learn about the following:
Opening and Saving WorkbooksReading Cells and SheetsCreating a Spreadsheet (adding / deleting rows and sheets, merging cells, folding, freeze panes)Cell Styling (font, alignment, side, border, images)Conditional FormattingChartsCommentsand more!After completing this course, you will be proficient in using the Python programming language to automate Microsoft Excel. This will make you more productive and valuable at your job. You can use the knowledge in this course to speed up your work day!
Python is a great language that you can use to enhance your daily work, whether you are an experienced developer or a beginner!
Where to PurchaseYou can get Automating Excel with Python, the video course, for 25% off for the next 30 days on Udemy by using the following coupon: FC79F40B55FC861DECAE
Automating Excel with Python is also available on Teach Me Python or Gumroad where it also includes the book in addition to the video course.
The post NEW COURSE: Automating Excel with Python on Udemy appeared first on Mouse Vs Python.
February 7, 2024
Episode 27 – Python Formatters with Lukasz Langa
Episode 27 of The Python Show Podcast welcomes Lukasz Langa as our guest.
Lukasz is a CPython Developer in Residence, which means he works full-time on the core CPython language. He is also the creator of Black, a super popular Python code formatter.
In this episode, we talked about the following topics:
Core python developmentThe origin of BlackYAPF and RuffPython, Python, Pythonand more!LinksYou can follow or connect with ?ukasz at the following sites:
X / TwitterPersonal websiteThe post Episode 27 – Python Formatters with Lukasz Langa appeared first on Mouse Vs Python.
February 6, 2024
Creating a Modal Dialog For Your TUIs in Textual
Textual is a Python package that you can use to create beautiful text-based user interfaces (TUIs). In other words, you can create a GUI in your terminal with Textual.
In this tutorial, you will learn how to create a modal dialog in your terminal. Dialogs are great ways to alert the user about something or get some input. You also see dialogs used for such things as settings or help.
Let’s get started!
Adding a Modal DialogThe first step is to think up some kind of application that needs a dialog. For this tutorial, you will create a form allowing the user to enter a name and address. Your application won’t save any data as that is outside the scope of this article, but it will demonstrate how to create the user interface and you can add that functionality yourself later on, if you wish.
To start, create a new file and name it something like tui_form.py. Then enter the following code:
from textual.app import App, ComposeResultfrom textual.containers import Center
from textual.containers import Grid
from textual.screen import ModalScreen
from textual.widgets import Button, Footer, Header, Input, Static, Label
class QuitScreen(ModalScreen):
"""Screen with a dialog to quit."""
def compose(self) -> ComposeResult:
yield Grid(
Label("Are you sure you want to quit?", id="question"),
Button("Quit", variant="error", id="quit"),
Button("Cancel", variant="primary", id="cancel"),
id="dialog",
)
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "quit":
self.app.exit()
else:
self.app.pop_screen()
class Form(Static):
def compose(self) -> ComposeResult:
"""
Creates the main UI elements
"""
yield Input(id="first_name", placeholder="First Name")
yield Input(id="last_name", placeholder="Last Name")
yield Input(id="address", placeholder="Address")
yield Input(id="city", placeholder="City")
yield Input(id="state", placeholder="State")
yield Input(id="zip_code", placeholder="Zip Code")
yield Input(id="email", placeholder="email")
with Center():
yield Button("Save", id="save_button")
class AddressBookApp(App):
CSS_PATH = "modal.tcss"
BINDINGS = [("q", "request_quit", "Quit")]
def compose(self) -> ComposeResult:
"""
Lays out the main UI elemens plus a header and footer
"""
yield Header()
yield Form()
yield Footer()
def action_request_quit(self) -> None:
"""Action to display the quit dialog."""
self.push_screen(QuitScreen())
if __name__ == "__main__":
app = AddressBookApp()
app.run()
Since this code is a little long, you will review it piece by piece. You will start at the bottom since the main entry point is the AddressBookApp class.
Here’s the code:
class AddressBookApp(App):CSS_PATH = "modal.tcss"
BINDINGS = [("q", "request_quit", "Quit")]
def compose(self) -> ComposeResult:
"""
Lays out the main UI elemens plus a header and footer
"""
yield Header()
yield Form()
yield Footer()
def action_request_quit(self) -> None:
"""Action to display the quit dialog."""
self.push_screen(QuitScreen())
if __name__ == "__main__":
app = AddressBookApp()
app.run()
The AddressBookApp class is your application code. Here, you create a header, the form itself, and the footer of your application. When the user presses the q button, you also set up an accelerator key or key binding that calls action_request_quit(). This will cause your modal dialog to appear!
But before you look at that code, you should check out your Form’s code:
class Form(Static):def compose(self) -> ComposeResult:
"""
Creates the main UI elements
"""
yield Input(id="first_name", placeholder="First Name")
yield Input(id="last_name", placeholder="Last Name")
yield Input(id="address", placeholder="Address")
yield Input(id="city", placeholder="City")
yield Input(id="state", placeholder="State")
yield Input(id="zip_code", placeholder="Zip Code")
yield Input(id="email", placeholder="email")
with Center():
yield Button("Save", id="save_button")
The Form class has a series of Input() widgets, which are text boxes, that you can enter your address information into. You specify a unique id for each widgets to give you a way to style each of them. You can read more about how that works in Using CSS to Style a Python TUI with Textual. The placeholder parameter lets you add a label to the text control so the user knows what should be entered in the widget.
Now you are ready to move on and look at your modal dialog code:
class QuitScreen(ModalScreen):"""Screen with a dialog to quit."""
def compose(self) -> ComposeResult:
yield Grid(
Label("Are you sure you want to quit?", id="question"),
Button("Quit", variant="error", id="quit"),
Button("Cancel", variant="primary", id="cancel"),
id="dialog",
)
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "quit":
self.app.exit()
else:
self.app.pop_screen()
The QuitScreen class is made up of two functions:
compose() – Creates the widgets in the modal dialogon_button_pressed() – The event handler that is fired when a button is pressedThe application will exit if the user presses the “Quit” button. Otherwise, the dialog will be dismissed, and you’ll return to your form screen.
You can style your application, including the modal dialog, using CSS. If you scroll back up to your application class, you’ll see that it refers to a CSS_PATH that points to a file named modal.tcss.
Here’s the CSS code that you’ll need to add to that file:
QuitScreen {align: center middle;
}
#dialog {
grid-size: 2;
grid-gutter: 1 2;
grid-rows: 1fr 3;
padding: 0 1;
width: 60;
height: 11;
border: thick $background 80%;
background: $surface;
}
#question {
column-span: 2;
height: 1fr;
width: 1fr;
content-align: center middle;
}
Button {
width: 100%;
}
This CSS will set the size and location of your modal dialog on the application. You tell Textual that you want the buttons to be centered and the dialog to be centered in the application.
To run your code, open up your terminal (or cmd.exe / Powershell on Windows), navigate to the folder that has your code in it, and run this command:
python tui_form.pyWhen you run this command, the initial screen will look like this:
To see the dialog, click the Save button to take the focus out of the text controls. Then hit the q button, and you will see the following:
You’ve done it! You created a modal dialog in your terminal!
Wrapping UpTextual is a great Python package. You can create rich, expressive user interfaces in your terminal. These GUIs are also lightweight and can be run in your browser via Textual-web.
Want to learn more about Textual? Check out some of the following tutorials:
An Intro to Textual – Creating Text User Interfaces with PythonTextual 101 – Using the TabbedContent WidgetUsing CSS to Style a Python TUI with Textual
The post Creating a Modal Dialog For Your TUIs in Textual appeared first on Mouse Vs Python.
December 5, 2023
Viewing an Animated GIF with Python
Animated GIFs are a fun way to share silent videos on social media. This website has a tutorial to help you learn how to create your own animated GIFs with Python. But what if you wanted to view an animated GIF with Python?
If you’re wondering if Python can present an animated GIF to the viewer, then you’ve found the right tutorial!
You will learn how to display a GIF with Python using the following methods:
Using tkinter to view an animated GIFUsing PySimpleGUI to view an animated GIFUsing Jupyter Notebook to view an animated GIFGetting StartedThe first step is to find an animated GIF you’d like to display. You can get GIFs from Google or Giphy. There are also many applications that you can use to make your own GIFs.
For the purposes of this tutorial, you can use this silly example GIF that shows a “hello world” example from Asciimatics, a Python TUI package:
Save this file as asicmatics_hello.gif to your computer so you can use it in the examples in this tutorial.
Now that you have an animated GIF, you are ready to learn how to display it using Python!
Viewing the Animated GIF with tkinterStackOverflow has many suggestions you can use to view animated GIFs with Python. One suggestion was to use tkinter, the Python GUI toolkit included with Python, to view an animated GIF.
The following code is a cleaned up variation on the suggestion from that post:
from tkinter import *from PIL import Image, ImageTk
class MyLabel(Label):
def __init__(self, master, filename):
im = Image.open(filename)
seq = []
try:
while 1:
seq.append(im.copy())
im.seek(len(seq)) # skip to next frame
except EOFError:
pass # we're done
try:
self.delay = im.info['duration']
except KeyError:
self.delay = 100
first = seq[0].convert('RGBA')
self.frames = [ImageTk.PhotoImage(first)]
Label.__init__(self, master, image=self.frames[0])
temp = seq[0]
for image in seq[1:]:
temp.paste(image)
frame = temp.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.cancel = self.after(self.delay, self.play)
def play(self):
self.config(image=self.frames[self.idx])
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.cancel = self.after(self.delay, self.play)
class Main():
def __init__(self):
root = Tk()
self.anim = MyLabel(root, 'asciimatics_hello.gif')
self.anim.pack()
Button(root, text='stop', command=self.stop_it).pack()
root.mainloop()
def stop_it(self):
self.anim.after_cancel(self.anim.cancel)
main = Main()
This code will import tkinter and create a Label() widget. The label can contain all kinds of different things, including images. For this example, you will create a list of frames from the GIF and store them in self.frames as instances of ImageTk.PhotoImage.
Then you will call tkinter’s handy after() method to make it play the frames back after a short delay. You use this command to call play() recursively.
When you run this code, you should see the following:
https://www.blog.pythonlibrary.org/wp-content/uploads/2023/11/tk_viewer.mp4You’ll note that in Tkinter, it seems to default to playing the GIF in black-and-white. You can do some more searching yourself and see if you can find a way to make it display the GIF in color.
Now, let’s try viewing it with PySimpleGUI!
Viewing the Animated GIF with PySimpleGUITkinter isn’t the only GUI toolkit in town. You can also use PySimpleGUI, a wrapper around Tkinter, wxPython, and PyQt. If you’d like to know more, you can check out this brief intro PySimpleGUI.
You will need to install PySimpleGUI since it doesn’t come with Python. You can use pip to do that:
python -m pip install pysimpleguiNow you’re ready to write some code. The following code is based on an example from the PySimpleGUI GitHub page:
import PySimpleGUI as sgfrom PIL import Image, ImageTk, ImageSequence
gif_filename = 'asciimatics_hello.gif'
layout = [[sg.Image(key='-IMAGE-')]]
window = sg.Window('Window Title', layout, element_justification='c', margins=(0,0), element_padding=(0,0), finalize=True)
interframe_duration = Image.open(gif_filename).info['duration']
while True:
for frame in ImageSequence.Iterator(Image.open(gif_filename)):
event, values = window.read(timeout=interframe_duration)
if event == sg.WIN_CLOSED:
exit(0)
window['-IMAGE-'].update(data=ImageTk.PhotoImage(frame) )
This code is a little shorter than the Tkinter example, so that’s pretty neat. Give it a try and see what happens!
Now you’re ready to try out viewing a GIF in Jupyter Notebook!
Viewing the Animated GIF in Jupyter NotebookJupyter Notebooks are great ways to share code along with some markup. You can create presentations, code examples, and their output and even widgets using Jupyter.
You can also insert images into Jupyter Notebook cells. That includes animated GIFs too! If you’d like to learn more about Jupyter Notebook, you should check out this introductory tutorial.
You’ll need to install Jupyter to be able to follow along with this part of the tutorial. Fortunately, that’s only a pip-install away:
python -m pip install jupyterNow that you have Jupyter Notebook installed, open up your terminal or Powershell and run the following command:
jupyter notebookThe next step is to create a new Notebook. Click the New button on the top right in the new web page that should have loaded in your default browser. Look for a URL like this: http://localhost:8888/tree
You will be presented with several choices when you click the New button. You should pick the top choice, which is Notebook. A new browser tab will open, and you may see a pop-up window asking which Kernel to choose. The default will probably be Python 3, which is what you want. Pick that, and you should be good to go!
In the middle of the toolbar along the top of the Jupyter Notebook Window, you will see a drop-down labeled Code. Click on that and change it to Markdown. Now the current cell is n Markdown mode instead of Code mode. That’s great!
Enter the following into your cell:
Make sure that asciimatics_hello.gif is in the same folder as your new Jupyter Notebook is in. Or you can put the absolute path to the file in there instead.
Now, you need to run the cell to see the animated GIF. You can click the play button in the toolbar or press SHIFT+ENTER. Either way that should run the cell.
At this point, you should see the following:
https://www.blog.pythonlibrary.org/wp-content/uploads/2023/11/jupyter_gif.mp4You did it! That looks great!
Wrapping UpPython has many different ways to view animated GIFs. You can use the built-in Tkinter GUI package, the PySimpleGUI package, or Jupyter Notebook.
There are probably others you can use as well. Feel free to drop a comment and let us all know what version you like best or a different package that you’ve tried.
The post Viewing an Animated GIF with Python appeared first on Mouse Vs Python.
November 27, 2023
Episode 23 – The Ruff Formatter with Charlie Marsh
The Ruff linter is a Python linter written in Rust that is super fast. The people behind Ruff recently released a new tool that is a part of Ruff that allows Ruff to format your Python code using the Black rules.
In this episode, I speak with Charlie Marsh, the original creator of Ruff and the founder of Astral, the company behind Ruff.
In this episode, we talked about:
The Ruff formatter and linterHow Ruff came aboutThe hardest features to createThe future of RuffPython vs Rustand more!The post Episode 23 – The Ruff Formatter with Charlie Marsh appeared first on Mouse Vs Python.