Mike Driscoll: Book Review: Serious Python

No Starch Press asked me to do a technical review of one of their upcoming books, “Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More” by Julien Danjou last year. I had never worked with No Starch before, but decided to give them a try and see how they differed from Packt Publishing. I ended up liking their process and the book was fun to read as well. It should be noted that No Starch did not ask me to do a book review. They only wanted me to do a technical review for them before the book was published.

I am writing this review because I think this book should get a little bit more notice. Also I interviewed its author a few years ago, so you might want to check that out too.


Quick Review

  • Why I picked it up: Originally, the publisher asked me to do a technical review
  • Why I finished it: The book covers intermediate level material and has an engaging writing style
  • I’d give it to: Beginners that want to grow beyond just knowing Python’s syntax

  • Book Formats

    You can get this book as a paperback, PDF, Mobi, or ePub.


    Book Contents

    This book contains 13 chapters across 240 pages. This book covers Python 2 and 3.

    Continue reading “Mike Driscoll: Book Review: Serious Python”

    Mike Driscoll: PyDev of the Week: Mariusz Felisiak

    This week we welcome Mariusz Felisiak (@MariuszFelisiak) as our PyDev of the Week! Mariusz is a core developer of the Django web framework and a maintainer of the django-request package. You can follow Mariusz over on Github to see what he’s been up to. Let’s spend some time getting to know Mariusz!

    Can you tell us a little about yourself (hobbies, education, etc):

    Few facts from my life. I’m a software developer with over 11 years of experience in designing and implementing web applications. I graduated in Computer Science in 2010. I defended my PhD thesis related with numerical algorithms in 2018. I’ve done this after few years of coping in the same time with open source activities, daily job and PhD studies. It was a really intense time.

    I’m always eager to contribute to open source projects which takes a large part of my free time, or at least it took before my daughter was born 🙂 I have been in love with Python and Django for 10 years. From 2017 I’m a member of the Django Core Team and the Django Software Foundations. In the middle of March I’m starting as a Django Fellow so Django will become my daily work! The funniest thing is that I should have more “free-time” 🙂 I’m a huge fan of open source and communities that stand behind them, that’s why I’m trying to be as involved as possible.

    Outside of the tech world I’m a speedway fan who spends free-time on traveling and winter mountaineering.

    Why did you start using Python?

    I started my professional career from ancient Oracle’s tools e.g. Oracle Forms & Reports. In 2009, we decided to write all new apps in a more modern framework, finally Python and Django were chosen. I had a sketchy knowledge of Python, so I’ve learned Python and Django in the same time 🙂 and I’ve never looked back.

    What other programming languages do you know and which is your favorite?

    I know SQL, PL/SQL, Java, JavaScript, HTML, CSS, C and C++. I probably also know how to write “Hello World” in few other programming languages. C and C++ are my favorite since I used them heavily in my studies and PhD.

    What projects are you working on now?

    I spend most of my time on daily work and Django itself. I’m also maintaining django-request package. In my daily work I maintain and develop RPR platform that connects healthcare stakeholders with global payer network. In Django, I’m mainly involved in the Django ORM.

    What non-Python open source projects do you enjoy using?

    I would say that vim is in the first place because I use it for writing code. Probably I’m old fashioned but that’s all I need. I don’t use any IDE 🙂

    How did you end up becoming a Django core developer?

    I worked for almost 10 years with Oracle databases and in the same time I used Django heavily. It seems that is not a common combination. When in 2015 Django folks posted a request for help in maintaining of the Oracle back-end and related CI infrastructure, I decided that is the best moment to help.

    I was really surprised with such a friendly welcome, as a person that nobody knows I started to be responsible for Oracle’s CI infrastructure. Contributing to Django became a part of my daily routine. Checking new tickets, finding bugs, optimizations, small clean-ups, reviewing PRs etc. In February 2017 Django devs invited me to the Core Team which was really unexpected. I’ve never taken into account that I could become part of such a smart collection of people. It wouldn’t be possible without help from the entire Django community and especially from Tim Graham, Shai Berger, and Simon Charette. Thanks!

    Is there anything else you’d like to say?

    Believe in your dreams and be involved!

    Thanks for doing the interview, Mariusz!

    Planet Python

    Mike Driscoll: Pros and Cons of Indy Publishing

    I personally really love self-publishing or Indy Publishing, so I am a little biased. In this article, I will go over what I think are the pros and cons of Indy Publishing versus going with a “real” publisher.

    Pros

    Here are my favorite parts about indy publishing:

    • I control the release date
    • I control the content
    • eBooks can be updated within minutes
    • Your royalty rate is 70-90%
    • Prices can be changed in seconds
    • Flash sales are easy
    • It looks good on a resume / cv

    I’m going to expand a bit on some of these points. I have worked with two publishers as an author: Packt Publishing and Apress. Packt has very aggressive timelines for getting things done. Chapters have to be done according to the schedule. A publisher can throw you curveballs when you are getting close to the end as well. When you self-publish, you control all of that.

    When I want to fix errata in my book, change an example or add a chapter, I can just do that and send out the update.

    If I want to give my book(s) away for free to students or whoever I want to, I can do that too. I donate books to local python user groups too. Feel free to contact me if you’d like some swag for your group. I may charge shipping if you live a long ways away though.

    Leanpub, Amazon and Gumroad have reports you can look at to see how well your book is doing. These are very useful.

    Finally I wanted to point out that employers don’t seem to care if the book was self-published or done through a publisher. Either way, they are usually interested and/or impressed.

    Cons

    Here are some cons that I have learned about from indy publishing:

    • You don’t get an editor
    • No technical reviewers
    • No marketing department
    • No art department

    After working with a couple of publishers, I noticed I didn’t really get any useful feedback from editors. I have worked with No Starch Press as a technical reviewer and I thought they gave better feedback to the author, but I only saw a little of that so I don’t really know how much they actually received.

    I did have a couple of technical reviewers on my wxPython Recipes book. That was helpful, although not as much as I thought it would be. As I mentioned in my previous post, I usually use my blog and Kickstarter to get feedback about my books before I launch them and that works as well or better.

    It is nice to have someone else do the marketing. Packt even assigned a publicist to me briefly. And Apress was helpful in giving me ideas about more consistent styling of the chapters and sections.

    The biggest con in a way is that you have to pay for everything. Artwork is expensive. Advertising is expensive too. You have to keep an eye on all of that and figure out what you want to spend and how you want to spend it.

    Negotiating Contracts

    When you self-publish or just blog a lot, publishers will probably come knocking and ask you to write for them. Or they might ask to buy the rights to your book and reprint them under their branding. While I don’t have a lot of experience negotiating contracts, I will mention a few points.

    If you are not well known in whatever community you want to sell to, that will hurt you at the negotiating table. Make sure you have the publisher’s time table before you decide on your final asking price.

    Writing a book is a time consuming and usually lonely process. Unless you already write a lot, it will most likely take you much longer than you expect. If the publisher wants you to do a convention, make sure to ask for your compensation to go up. They may not pay for everything, but they will usually bump it up a bit.

    One other thing I want to mention is that the advance that you get paid may be all that you get paid for the book. In fact, it is best to just think that is what is going to happen so you don’t get disappointed. Let’s crunch some numbers. Most publishers pay around 10% as their royalty rate. Now let’s say you get a $ 4000 advance. You don’t start getting royalties when they hit $ 4000. Instead you get paid when your royalty amount goes over $ 4000.

    If the book is selling for $ 25, your royalty will be something like $ 1.25. You would need to sell over 3000 books before you start getting royalties. Sadly you will probably never get there.

    You can read more about this topic and writing books in general here.

    I think the biggest positive I had when working with publishers is getting one of my books in a Humble Bundle. As an indy publisher, I can’t get into those. Will I make any money from that? I don’t know. The royalties for bundles are small and only find out how well your book is doing on a quarterly basis at best.

    Wrapping Up

    I really enjoy publishing my own books. I like the freedom it gives me with the content and the ability to share my content however I see fit. I have learned a lot from working with publishers though. They certainly have their place. But I think you can do just as well without them if you are willing to put in the work.

    Planet Python

    Mike Driscoll: PyDev of the Week: Maria McKinley

    This week we welcome Maria McKinley (@twiteness) as our PyDev of the Week. Maria is a Senior Software Engineer at the Walt Disney Company and will be a speaker at PyCascades 2019. She is also teaching the Python Certificate Program at the University of Washington Continuing Education. Let’s spend a few moments getting to know her better.

    http://www.mariakathryn.net/Blog/Blog

    Can you tell us a little about yourself (hobbies, education, etc):

    I have a BS in Physics from the University of Washington, and taught myself how to code while working in Neuroscience labs at the same University. I got to work on some amazing research projects, while discovering how much I enjoyed writing code. In October 2015 I started working at the Walt Disney Company as a Senior Software Engineer. I also teach Python, both at the University of Washington and within Disney. And I’m a mom. All of that keeps me pretty busy, but I also try to set aside time for reading, exercise, playing boardgames, and art.

    Why did you start using Python?

    While I was working in the Neuroscience labs, I often did both software development and system administration. A few years ago, I was running a mail server, and trying to automate some administrative task related to spam. It wasn’t a terribly important or frequent one, so every once in a while I would work on automating it with a Bash script. After a few months, someone told me Python was good for sysadmin, so I tried it. In five minutes, I was able to get a script running, doing the task that had alluded me for so long. I was hooked.

    What other programming languages do you know and which is your favorite?

    Python is my favorite, and I’ve ben using it pretty exclusively for the last five years or so. I have used Matlab, Javascript, C, C#, C++, Actionscript, Igor, and PHP enough to have a basic understanding. I wouldn’t say I know them all anymore, but I did at one point to varying degrees. Just like a foreign language, if you don’t use it you lose it. I can still read them all, though, so there’s that. I taught myself basic when I was young, and I still remember having to change a bunch of the goto statements when I wanted to add something in the middle. That was hell. Python is better. 🙂

    What projects are you working on now?

    At the moment, I’m mostly working on teaching, and preparing a talk for PyCascades. I have dreams of playing around with Blender more, but that is going to have to wait for a couple of months. I have a couple of projects at work, as well. Those are REST APIs for backend SysOps colleagues, mostly.

    What non-Python open source projects do you enjoy using?

    Linux. Okay, I guess I have to go with a Python one, Blender.

    How did you end up teaching Python in a university?

    While I was at the university, I figured out that since I was self-taught, I did not know what I did not know. So one of the things I did to start figuring out where the holes were was to started a programming group at the university for secluded-in-a-lab-somewhere software developers to get together to learn from each other. The people teaching Python at the university found out about it, and asked me to post about openings they had. So, I did, and then applied myself.

    What do students struggle with the most when learning Python?

    I wish there were one thing that students struggle with most that we could just fix. Part of it depends on whether they are new to programming or not. People who are new to programming have an entirely different set of problems from those coming from a different language, and honestly, when taught together they can both get frustrated. I would say one of the biggest issues for beginning programmers is mindset. They get frustrated because they can’t write code the first time or that works, not realizing that that is true for experienced programmers, as well. So much of programming is trial and error, and that is not emphasized enough. If you get frustrated when things don’t go right, you will be frustrated most of the time as a developer, especially in the first few years.

    How can the Python community make this better?

    I think every class or tutorial for beginners should begin by encouraging students to embrace troubleshooting as a fun challenge or game. It is all about learning from your mistakes, and realizing that making mistakes is actually one of the best ways to learn. Teaching is also a great way to learn, so help your fellow students!

    Is there anything else you’d like to say?

    Super looking forward to adaptation of Good Omens to a television series. That book has a special place in my heart.

    Thanks for doing the interview, Maria!

    Planet Python

    Mike Driscoll: Creating a Calculator with wxPython

    A lot of beginner tutorials start with “Hello World” examples. There are plenty of websites that use a calculator application as a kind of “Hello World” for GUI beginners. Calculators are a good way to learn because they have a set of widgets that you need to lay out in an orderly fashion. They also require a certain amount of logic to make them work correctly. For this calculator, let’s focus on being able to do the following:

    • Addition
    • Subtraction
    • Multiplication
    • Division

    I think that supporting these four functions is a great starting place and also give you plenty of room for enhancing the application on your own.


    Figuring Out the Logic

    One of the first items that you will need to figure out is how to actually execute the equations that you build. For example, let’s say that you have the following equation:


    1 + 2 * 5

    What is the solution? If you read it left-to-right, the solution would seem to be 3 * 5 or 15. But multiplication has a higher precedence than addition, so it would actually be 10 + 1 or 11. How do you figure out precedence in code? You could spend a lot of time creating a string parser that groups numbers by the operand or you could use Python’s built-in `eval` function. The eval() function is short for evaluate and will evaluate a string as if it was Python code.

    A lot of Python programmers actually discourage the user of eval(). Let’s find out why.


    Is eval() Evil?

    The eval() function has been called “evil” in the past because it allows you to run strings as code, which can open up your application’s to nefarious evil-doers. You have probably read about SQL injection where some websites don’t properly escape strings and accidentally allowed dishonest people to edit their database tables by running SQL commands via strings. The same concept can happen in Python when using the eval() function. A common example of how eval could be used for evil is as follows:

    eval("__import__('os').remove('file')")

    This code will import Python’s os module and call its remove() function, which would allow your users to delete files that you might now want them to delete. There are a couple of approaches for avoiding this issue:

    • Don’t use eval()
    • Control what characters are allowed to go to eval()

    Since you will be creating the user interface for this application, you will also have complete control over how the user enters characters. This actually can protect you from eval’s insidiousness in a straight-forward manner. You will learn two methods of using wxPython to control what gets passed to eval(), and then you will learn how to create a custom eval() function at the end of the article.


    Designing the Calculator

    Let’s take a moment and try to design a calculator using the constraints mentioned at the beginning of the chapter. Here is the sketch I came up with:

    Calculator mockup

    Note that you only care about basic arithmetic here. You won’t have to create a scientific calculator, although that might be a fun enhancement to challenge yourself with. Instead, you will create a nice, basic calculator.

    Let’s get started!


    Creating the Initial Calculator

    Whenever you create a new application, you have to consider where the code will go. Does it go in the wx.Frame class, the wx.Panel class, some other class or what? It is almost always a mix of different classes when it comes to wxPython. As is the case with most wxPython applications, you will want to start by coming up with a name for your application. For simplicity’s sake, let’s call it wxcalculator.py for now.

    The first step is to add some imports and subclass the Frame widget. Let’s take a look:

    import wx   class CalcFrame(wx.Frame):       def __init__(self):         super().__init__(             None, title="wxCalculator",             size=(350, 375))         panel = CalcPanel(self)         self.SetSizeHints(350, 375, 350, 375)         self.Show()     if __name__ == '__main__':     app = wx.App(False)     frame = CalcFrame()     app.MainLoop()

    This code is very similar to what you have seen in the past. You subclass wx.Frame and give it a title and initial size. Then you instantiate the panel class, CalcPanel (not shown) and you call the SetSizeHints() method. This method takes the smallest (width, height) and the largest (width, height) that the frame is allowed to be. You may use this to control how much your frame can be resized or in this case, prevent any resizing. You can also modify the frame’s style flags in such a way that it cannot be resized too.

    Here’s how:

    class CalcFrame(wx.Frame):       def __init__(self):         no_resize = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER |                                                  wx.MAXIMIZE_BOX)         super().__init__(             None, title="wxCalculator",             size=(350, 375), style=no_resize)         panel = CalcPanel(self)         self.Show()

    Take a look at the no_resize variable. It is creating a wx.DEFAULT_FRAME_STYLE and then using bitwise operators to remove the resizable border and the maximize button from the frame.

    Let’s move on and create the CalcPanel:

    class CalcPanel(wx.Panel):       def __init__(self, parent):         super().__init__(parent)         self.last_button_pressed = None         self.create_ui()

    I mentioned this in an earlier chapter, but I think it bears repeating here. You don’t need to put all your interfacer creation code in the init method. This is an example of that concept. Here you instantiate the class, set the last_button_pressed attribute to None and then call create_ui(). That is all you need to do here.

    Of course, that begs the question. What goes in the create_ui() method? Well, let’s find out!

    def create_ui(self):     main_sizer = wx.BoxSizer(wx.VERTICAL)     font = wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL)       self.solution = wx.TextCtrl(self, style=wx.TE_RIGHT)     self.solution.SetFont(font)     self.solution.Disable()     main_sizer.Add(self.solution, 0, wx.EXPAND|wx.ALL, 5)     self.running_total = wx.StaticText(self)     main_sizer.Add(self.running_total, 0, wx.ALIGN_RIGHT)       buttons = [['7', '8', '9', '/'],                ['4', '5', '6', '*'],                ['1', '2', '3', '-'],                ['.', '0', '', '+']]     for label_list in buttons:         btn_sizer = wx.BoxSizer()         for label in label_list:             button = wx.Button(self, label=label)             btn_sizer.Add(button, 1, wx.ALIGN_CENTER|wx.EXPAND, 0)             button.Bind(wx.EVT_BUTTON, self.update_equation)         main_sizer.Add(btn_sizer, 1, wx.ALIGN_CENTER|wx.EXPAND)       equals_btn = wx.Button(self, label='=')     equals_btn.Bind(wx.EVT_BUTTON, self.on_total)     main_sizer.Add(equals_btn, 0, wx.EXPAND|wx.ALL, 3)       clear_btn = wx.Button(self, label='Clear')     clear_btn.Bind(wx.EVT_BUTTON, self.on_clear)     main_sizer.Add(clear_btn, 0, wx.EXPAND|wx.ALL, 3)       self.SetSizer(main_sizer)

    This is a decent chunk of code, so let’s break it down a bit:

    def create_ui(self):     main_sizer = wx.BoxSizer(wx.VERTICAL)     font = wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL)

    Here you create the sizer that you will need to help organize the user interface. You will also create a wx.Font object, which is used to modifying the default font of widgets like wx.TextCtrl or wx.StaticText. This is helpful when you want a larger font size or a different font face for your widget than what comes as the default.

    self.solution = wx.TextCtrl(self, style=wx.TE_RIGHT) self.solution.SetFont(font) self.solution.Disable() main_sizer.Add(self.solution, 0, wx.EXPAND|wx.ALL, 5)

    These next three lines create the wx.TextCtrl, set it to right-justified (wx.TE_RIGHT), set the font and `Disable()` the widget. The reason that you want to disable the widget is because you don’t want the user to be able to type any string of text into the control.

    As you may recall, you will be using eval() for evaluating the strings in that widget, so you can’t allow the user to abuse that. Instead, you want fine-grained control over what the user can enter into that widget.

    self.running_total = wx.StaticText(self) main_sizer.Add(self.running_total, 0, wx.ALIGN_RIGHT)

    Some calculator applications have a running total widget underneath the actual “display”. A simple way to add this widget is via the wx.StaticText widget.

    Now let’s add main buttons you will need to use a calculator effectively:

    buttons = [['7', '8', '9', '/'],            ['4', '5', '6', '*'],            ['1', '2', '3', '-'],            ['.', '0', '', '+']] for label_list in buttons:     btn_sizer = wx.BoxSizer()     for label in label_list:         button = wx.Button(self, label=label)         btn_sizer.Add(button, 1, wx.ALIGN_CENTER|wx.EXPAND, 0)         button.Bind(wx.EVT_BUTTON, self.update_equation)     main_sizer.Add(btn_sizer, 1, wx.ALIGN_CENTER|wx.EXPAND)

    Here you create a list of lists. In this data structure, you have the primary buttons used by your calculator. You will note that the there is a blank string in the last list that will be used to create a button that doesn’t do anything. This is to keep the layout correct. Theoretically, you could update this calculator down the road such that that button could be percentage or do some other function.

    The next step is to create a the buttons, which you can do by looping over the list. Each nested list represents a row of buttons. So for each row of buttons, you will create a horizontally oriented wx.BoxSizer and then loop over the row of widgets to add them to that sizer. Once every button is added to the row sizer, you will add that sizer to your main sizer. Note that each of these button’s is bound to the `update_equation` event handler as well.

    Now you need to add the equals button and the button that you may use to clear your calculator:

    equals_btn = wx.Button(self, label='=') equals_btn.Bind(wx.EVT_BUTTON, self.on_total) main_sizer.Add(equals_btn, 0, wx.EXPAND|wx.ALL, 3)   clear_btn = wx.Button(self, label='Clear') clear_btn.Bind(wx.EVT_BUTTON, self.on_clear) main_sizer.Add(clear_btn, 0, wx.EXPAND|wx.ALL, 3)   self.SetSizer(main_sizer)

    In this code snippet you create the “equals” button which you then bind to the on_total event handler method. You also create the “Clear” button, for clearing your calculator and starting over. The last line sets the panel’s sizer.

    Let’s move on and learn what most of the buttons in your calculator are bound to:

    def update_equation(self, event):     operators = ['/', '*', '-', '+']     btn = event.GetEventObject()     label = btn.GetLabel()     current_equation = self.solution.GetValue()       if label not in operators:         if self.last_button_pressed in operators:             self.solution.SetValue(current_equation + ' ' + label)         else:             self.solution.SetValue(current_equation + label)     elif label in operators and current_equation is not '' \          and self.last_button_pressed not in operators:         self.solution.SetValue(current_equation + ' ' + label)       self.last_button_pressed = label       for item in operators:         if item in self.solution.GetValue():             self.update_solution()             break

    This is an example of binding multiple widgets to the same event handler. To get information about which widget has called the event handler, you can call the `event` object’s GetEventObject() method. This will return whatever widget it was that called the event handler. In this case, you know you called it with a wx.Button instance, so you know that wx.Button has a `GetLabel()` method which will return the label on the button. Then you get the current value of the solution text control.

    Next you want to check if the button’s label is an operator (i.e. /, *, -, +). If it is, you will change the text controls value to whatever is currently in it plus the label. On the other hand, if the label is not an operator, then you want to put a space between whatever is currently in the text box and the new label. This is for presentation purposes. You could technically skip the string formatting if you wanted to.

    The last step is to loop over the operands and check if any of them are currently in the equation string. If they are, then you will call the update_solution() method and break out of the loop.

    Now you need to write the update_solution() method:

    def update_solution(self):     try:         current_solution = str(eval(self.solution.GetValue()))         self.running_total.SetLabel(current_solution)         self.Layout()         return current_solution     except ZeroDivisionError:         self.solution.SetValue('ZeroDivisionError')     except:         pass

    Here is where the “evil” eval() makes its appearance. You will extract the current value of the equation from the text control and pass that string to eval(). Then convert that result back to a string so you can set the text control to the newly calculated solution. You want to wrap the whole thin in a try/except statement to catch errors, such as the ZeroDivisionError. The last except statement is known as a bare except and should really be avoided in most cases. For simplicity, I left it in there, but feel free to delete those last two lines if they offend you.

    The next method you will want to take a look at is the on_clear() method:

    def on_clear(self, event):     self.solution.Clear()     self.running_total.SetLabel('')

    This code is pretty straight-forward. All you need to do is call your solution text control’s Clear() method to empty it out. You will also want to clear the `running_total` widget, which is an instance of wx.StaticText. That widget does not have a Clear() method, so instead you will call SetLabel() and pass in an empty string.

    The last method you will need to create is the on_total() event handler, which will calculate the total and also clear out your running total widget:

    def on_total(self, event):     solution = self.update_solution()     if solution:         self.running_total.SetLabel('')

    Here you can call the update_solution() method and get the result. Assuming that all went well, the solution will appear in the main text area and the running total will be emptied.

    Here is what the calculator looks like when I ran it on a Mac:

    wxPython Calculator on Mac OS

    And here is what the calculator looks like on Windows 10:

    wxPython Calculator on Windows 10

    Let’s move on and learn how you might allow the user to use their keyboard in addition to your widgets to enter an equation.


    Using Character Events

    Most calculators will allow the user to use the keyboard when entering values. In this section, I will show you how to get started adding this ability to your code. The simplest method to use to make this work is to bind the wx.TextCtrl to the wx.EVT_TEXT event. I will be using this method for this example. However another way that you could do this would be to catch wx.EVT_KEY_DOWN and then analyze the key codes. That method is a bit more complex though.

    The first item that we need to change is our CalcPanel‘s constructor:

    # wxcalculator_key_events.py   import wx   class CalcPanel(wx.Panel):       def __init__(self, parent):         super().__init__(parent)         self.last_button_pressed = None         self.whitelist = ['0', '1', '2', '3', '4',                           '5', '6', '7', '8', '9',                           '-', '+', '/', '*', '.']         self.on_key_called = False         self.empty = True         self.create_ui()

    Here you add a whitelist attribute and a couple of simple flags, self.on_key_called and self.empty. The white list are the only characters that you will allow the user to type in your text control. You will learn about the flags when we actually get to the code that uses them.

    But first, you will need to modify the create_ui() method of your panel class. For brevity, I will only reproduce the first few lines of this method:

    def create_ui(self):     main_sizer = wx.BoxSizer(wx.VERTICAL)     font = wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL)       self.solution = wx.TextCtrl(self, style=wx.TE_RIGHT)     self.solution.SetFont(font)     self.solution.Bind(wx.EVT_TEXT, self.on_key)     main_sizer.Add(self.solution, 0, wx.EXPAND|wx.ALL, 5)     self.running_total = wx.StaticText(self)     main_sizer.Add(self.running_total, 0, wx.ALIGN_RIGHT)

    Feel free to download the full source from Github or refer to the code in the previous section. The main differences here in regards to the text control is that you are no longer disabling it and you are binding it to an event: wx.EVT_TEXT.

    Let’s go ahead an write the on_key() method:

    def on_key(self, event):     if self.on_key_called:         self.on_key_called = False         return       key = event.GetString()     self.on_key_called = True       if key in self.whitelist:         self.update_equation(key)

    Here you check to see if the self.on_key_called flag is True. If it is, we set it back to False and `return` early. The reason for this is that when you use your mouse to click a button, it will cause EVT_TEXT to fire. The `update_equation()` method will get the contents of the text control which will be the key we just pressed and add the key back to itself, resulting in a double value. This is one way to workaround that issue.

    You will also note that to get the key that was pressed, you can call the event object’s GetString() method. Then you will check to see if that key is in the white list. If it is, you will update the equation.

    The next method you will need to update is update_equation():

    def update_equation(self, text):     operators = ['/', '*', '-', '+']     current_equation = self.solution.GetValue()       if text not in operators:         if self.last_button_pressed in operators:             self.solution.SetValue(current_equation + ' ' + text)         elif self.empty and current_equation:             # The solution is not empty             self.empty = False         else:             self.solution.SetValue(current_equation + text)     elif text in operators and current_equation is not '' \          and self.last_button_pressed not in operators:         self.solution.SetValue(current_equation + ' ' + text)       self.last_button_pressed = text     self.solution.SetInsertionPoint(-1)       for item in operators:         if item in self.solution.GetValue():             self.update_solution()             break

    Here you add a new elif that checks if the self.empty flag is set and if the current_equation has anything in it. In other words, if it is supposed to be empty and it’s not, then we set the flag to False because it’s not empty. This prevents a duplicate value when the keyboard key is pressed. So basically you need two flags to deal with duplicate values that can be caused because you decided to allow users to use their keyboard.

    The other change to this method is to add a call to SetInsertionPoint() on your text control, which will put the insertion point at the end of the text control after each update.

    The last required change to the panel class happens in the on_clear() method:

    def on_clear(self, event):     self.solution.Clear()     self.running_total.SetLabel('')     self.empty = True     self.solution.SetFocus()

    This change was done by adding two new lines to the end of the method. The first is to reset self.empty back to True. The second is to call the text control’s SetFocus() method so that the focus is reset to the text control after it has been cleared.

    You could also add this SetFocus() call to the end of the on_calculate() and the on_total() methods. This should keep the text control in focus at all times. Feel free to play around with that on your own.


    Creating a Better eval()

    Now that you have looked at a couple of different methods of keeping the “evil” eval() under control, let’s take a few moments to learn how you can create a custom version of eval() on your own. Python comes with a couple of handy built-in modules called ast and operator. The ast module is an acronym that stands for “Abstract Syntax Trees” and is used “for processing trees of the Python abstract syntax grammar” according to the documentation. You can think of it as a data structure that is a representation of code. You can use the ast module to create a compiler in Python.

    The operator module is a set of functions that correspond to Python’s operators. A good example would be operator.add(x, y) which is equivalent to the expression x+y. You can use this module along with the `ast` module to create a limited version of eval().

    Let’s find out how:

    import ast import operator   allowed_operators = {ast.Add: operator.add, ast.Sub: operator.sub,                       ast.Mult: operator.mul, ast.Div: operator.truediv}   def noeval(expression):     if isinstance(expression, ast.Num):         return expression.n     elif isinstance(expression, ast.BinOp):         print('Operator: {}'.format(expression.op))         print('Left operand: {}'.format(expression.left))         print('Right operand: {}'.format(expression.right))         op = allowed_operators.get(type(expression.op))         if op:             return op(noeval(expression.left),                        noeval(expression.right))     else:         print('This statement will be ignored')   if __name__ == '__main__':     print(ast.parse('1+4', mode='eval').body)     print(noeval(ast.parse('1+4', mode='eval').body))     print(noeval(ast.parse('1**4', mode='eval').body))     print(noeval(ast.parse("__import__('os').remove('path/to/file')", mode='eval').body))

    Here you create a dictionary of allowed operators. You map ast.Add to operator.add, etc. Then you create a function called `noeval` that accepts an `ast` object. If the expression is just a number, you return it. However if it is a BinOp instance, than you print out the pieces of the expression. A BinOp is made up of three parts:

    • The left part of the expression
    • The operator
    • The right hand of the expression

    What this code does when it finds a BinOp object is that it then attempts to get the type of ast operation. If it is one that is in our allowed_operators dictionary, then you call the mapped function with the left and right parts of the expression and return the result.

    Finally if the expression is not a number or one of the approved operators, then you just ignore it. Try playing around with this example a bit with various strings and expressions to see how it works.

    Once you are done playing with this example, let’s integrate it into your calculator code. For this version of the code, you can call the Python script wxcalculator_no_eval.py. The top part of your new file should look like this:

    # wxcalculator_no_eval.py   import ast import operator   import wx     class CalcPanel(wx.Panel):       def __init__(self, parent):         super().__init__(parent)         self.last_button_pressed = None         self.create_ui()           self.allowed_operators = {             ast.Add: operator.add, ast.Sub: operator.sub,              ast.Mult: operator.mul, ast.Div: operator.truediv}

    The main differences here is that you now have a couple of new imports (i.e. ast and operator) and you will need to add a Python dictionary called self.allowed_operators. Next you will want to create a new method called noeval():

    def noeval(self, expression):     if isinstance(expression, ast.Num):         return expression.n     elif isinstance(expression, ast.BinOp):         return self.allowed_operators[             type(expression.op)](self.noeval(expression.left),                                   self.noeval(expression.right))     return ''

    This method is pretty much exactly the same as the function you created in the other script. It has been modified slightly to call the correct class methods and attributes however. The other change you will need to make is in the update_solution() method:

    def update_solution(self):     try:         expression = ast.parse(self.solution.GetValue(),                                mode='eval').body         current_solution = str(self.noeval(expression))         self.running_total.SetLabel(current_solution)         self.Layout()         return current_solution     except ZeroDivisionError:         self.solution.SetValue('ZeroDivisionError')     except:         pass

    Now the calculator code will use your custom eval() method and keep you protected from the potentially harmfulness of eval(). The code that is in Github has the added protection of only allowing the user to use the onscreen UI to modify the contents of the text control. However you can easily change it to enable the text control and try out this code without worrying about eval() causing you any harm.


    Wrapping Up

    In this chapter you learned several different approaches to creating a calculator using wxPython. You also learned a little bit about the pros and cons of using Python’s built-in eval() function. Finally, you learned that you can use Python’s ast and operator modules to create a finely-grained version of eval() that is safe for you to use. Of course, since you are controlling all input into eval(), you can also control the real version quite easily though your UI that you generate with wxPython.

    Take some time and play around with the examples in this article. There are many enhancements that could be made to make this application even better. When you find bugs or missing features, challenge yourself to try to fix or add them.


    Download the Source

    The source code for this article can be found on Github. This article is based on one of the chapters from my book, Creating GUI Applications with wxPython.

    Planet Python