There are a lot of computer languages that include the ternary (or tertiary) operator, which is basically a one-line conditional expression in Python. If you’re interested, you can read about the various ways it’s rendered in other languages over on Wikipedia. Here we will spend some time looking at several different examples and why you might use this operator in real life. Continue reading Python 101: The Ternary Operator
Some people complained about my last logging article, wondering if it was even necessary since the docs and Doug Hellman have already written on the topic. I sometimes wonder why I write on these topics too, but usually when I do, I get lots of readers. In this case, I’ve gotten almost 10,000 hits just on that one article in a week, so I guess there must still be room for me to write on topics like this. I received a couple of comments mentioned alternate logging libraries. One of these was lggr by Peter Downs. We’ll take a quick look at the project and see how it shapes up. The documentation is pretty shallow at this point, but let’s see what we can do. Continue reading Python logging with lggr
The other day, I stumbled across a question on StackOverflow asking how to get the children widgets of a BoxSizer. In wxPython, you would expect to call the sizer’s GetChildren() method. However, this returns a list of SizerItems objects rather than a list of the actual widgets themselves. You can see the difference if you call a wx.Panel’s GetChildren() method. Now I don’t ask a lot of questions on the wxPython users group list, but I was curious about this one and ended up receiving a quick answer from Cody Precord, author of the wxPython Cookbook and Editra. Anyway, he ended up pointing me in the right direction and I came up with the following bit of code:
Continue reading wxPython: How to Get Children Widgets from a Sizer
People keep on asking fun wxPython questions on StackOverflow. Today they wanted to know how to make “flashing text” in wxPython. That’s actually a pretty easy thing to do. Let’s take a look at some simple code:
import random import time import wx ######################################################################## class MyPanel(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) self.font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL) self.flashingText = wx.StaticText(self, label="I flash a LOT!") self.flashingText.SetFont(self.font) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.update, self.timer) self.timer.Start(1000) #---------------------------------------------------------------------- def update(self, event): """""" now = int(time.time()) mod = now % 2 print now print mod if mod: self.flashingText.SetLabel("Current time: %i" % now) else: self.flashingText.SetLabel("Oops! It's mod zero time!") colors = ["blue", "green", "red", "yellow"] self.flashingText.SetForegroundColour(random.choice(colors)) ######################################################################## class MyFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title="Flashing text!") panel = MyPanel(self) self.Show() #---------------------------------------------------------------------- if __name__ == "__main__": app = wx.App(False) frame = MyFrame() app.MainLoop()
Basically all you need is a wx.StaticText instance and a wx.Timer. In this example, the text will “flash” once a second. By flash, we mean it will change colors AND the text itself will change. The original person who made this question wanted to know how to display the time using Python’s time.time() method and they wanted the message to change depending on whether or not the modulus of the time by 2 was equal to zero. I realize that looks a little odd, but I’ve actually used that idea in some of my own code. Anyway, this worked for me on Windows 7 with Python 2.6.6 and wxPython 22.214.171.124.
Note that sometimes the SetForegroundColour method doesn’t work on all widgets across all platforms as the native widget doesn’t always allow the color to be changed, so your mileage may vary.
This week I bought Rick Copeland’s MongoDB with Python and Ming eBook from Amazon. It just came out in July 2012, so I figured I should check it out and see what all the fuss is with MongoDB and the whole NoSQL fad.
- Why I picked it up: Mainly because I’ve been interested in MongoDB for a while, the book was reasonably priced and I’ve read a little of his SQLAlchemy book. I think I may have even met the guy at PyCon a couple years ago too.
- Why I finished it: I almost always try to finish a book, especially if I’m going to review it. This one was hard though.
- I’d give it to: Someone who needed a quick text to get them up to speed on MongoDB and Ming
I am currently working on a book review for a college course Python book that uses the Python turtle module and Tkinter to help teach the Python programming language. Hopefully I’ll have that book done by the end of the month. In the mean time, it made me decide to give the turtle module a try. In this article we’ll look at making the turtle draw the typical Olympics symbol and then try to clean up the code while adding new features. Continue reading Python: Using Turtles for Drawing Circles
Think Complexity by Allen Downey is written for someone in an intermediate college level class. It has examples of Python code and talks about algorithms a lot. Personally, I think it would probably be suitable as a 300 level class or higher just because of all the math and science related stuff.
The author goes all over the place and references Wikipedia often. Chapter 1 is about Complexity Science, which seems to lean towards the idea of “question everything” and “ask questions” without
really caring about the answers. Chapter 2 is about graphs, but not graphing in the regular sense. Instead, the author is referring to a “system that contains discrete, interconnected elements”, such as a map. Chapter 3 is about the analysis of algorithms and has some interesting mini-studies about search algorithms and hash tables.
Chapter 4 is all about Small World Graphs and contains lots of references to scientists like Watts, Strogatz and Dijkstra. Chapter 5 deals with Scale-Free Networks and various types of distributions thereof. Chapter 6 introduces the concepts of Cellular Automata and the various levels that Stephen Wolfram came up with. This topic is continued in Chapter 7 with the Game of Life idea. As you can see, the chapters vary wildly in content both from chapter to chapter and within the chapters themselves. They are also very short as most clock in at around 10 pages. Chapters 8-10 talk about such heady topics as Fractals, Fourier transforms, and Agent-Based Models. The last 4 chapters are case studies.
There isn’t a lot of Python code in this book. It’s mostly an “ideas” book that’s designed to make the reader think. Some of the code examples are interesting though. For example, the author teaches the reader how to construct an abstract class in Python very clearly and how to design it so that it cannot be instantiated but must be sub-classed and overridden instead. The author also has a couple of examples where he uses SciPy or NumPy to illustrate some of his ideas, so this book will probably appeal the most to scientific Python programmers. One nice plus is that the author does have some interesting exercises for students to try, although he doesn’t provide the solutions in the book. I think some of the solutions can be found on the book’s website though.
If you’re looking for a rather random book on science with a smattering of code (or you just want to learn a little bit about Complexity Science), then this book might be for you. On the other hand, if you’re hoping to learn about actual Python code in the scientific world, then you’re not going to learn much from this work. I know this is a little contradictory to the previous paragraph, but while there are some small examples of equations using NumPy and SciPy, the vast majority of the book is prose. In the end, the book is interesting to read, but probably won’t add a lot to your programming toolkit.
Note: I received this book free of charge from the publisher
Earlier this week, I wrote a simple post about Python’s Queues and demonstrated how they can be used with a threading pool to download a set of PDFs from the United States Internal Revenue Service’s website. Today I decided to try “porting” that code over to Python’s multiprocessing module. As one of my readers pointed out, Python’s Queues and threads are limited to running on only one core due to the Global Interpreter Lock (GIL) that is a part of Python. The multiprocessing module (and Stackless and several other projects) can run on multiple cores and skirts around the GIL (see the documentation if you’re curious). Anyway, let’s get started. Continue reading Python Concurrency: Porting from a Queue to Multiprocessing
Python provides a very powerful logging library in its standard library. A lot of programmers use print statements for debugging (myself included), but you can also use logging to do this. It’s actually cleaner to use logging as you won’t have to go through all your code to remove the print statements. In this tutorial we’ll cover the following topics:
- Creating a simple logger
- How to log from multiple modules
- Log formatting
- Log configuration
By the end of this tutorial, you should be able to confidently create your own logs for your applications. Let’s get started! Continue reading Python 101: An Intro to logging
Python comes with a lot of cool concurrency tools builtin, such as threads, Queues, semaphores and multiprocessing. In this article, we’ll spend some time learning how to use Queues. A Queue can be used for first-in-first out or last-in-last-out stack-like implementations if you just use them directly. If you’d like to see that in action, see the Hellman article at the end of this post. We’re going to mix threads in and create a simple file downloader script to demonstrate how Queues work for cases where we want concurrency. Continue reading Python Concurrency: An Example of a Queue