Category Archives: Python 3

Book Review: Murach’s Python Programming

I review books for the i-programmer website from time to time and they recently gave me a copy of Murach’s Python Programming by Michael Urban and Joel Murach. This book is long at almost 600 pages and it’s pretty expensive for the paperback. For those of you with short attention spans, I give you the Quick Review. For those who would like something a bit more in-depth, you will need to click through to see the rest.


Quick Review

  • Why I picked it up: In this case, because i-programming asked me to
  • Why I finished it: Because this book is well written and fairly interesting
  • I’d give it to: Someone who wants to learn Python

Continue reading Book Review: Murach’s Python Programming

New in Python: Syntax for variable annotations

Python 3.6 added another interesting new feature that is known as Syntax for variable annotations. This new feature is outlined in PEP 526. The basic premise of this PEP is take the idea of Type Hinting (PEP 484) to its next logical step, which is basically adding option type definitions to Python variables, including class variables and instance variables. Please note that adding these annotations or definitions does not suddenly make Python a statically typed language. The interpreter still doesn’t care what type the variable is. However, a Python IDE or other utility like pylint could have an annotation checker added to them that could highlight when you use a variable that you have annotated as one type and then used incorrectly by changing its type mid-function.

Let’s look at a simple example so we can see how this works:

# annotate.py
name: str = 'Mike'

Continue reading New in Python: Syntax for variable annotations

New in Python: Underscores in Numeric Literals

Python 3.6 added some interesting new features. The one that we will be looking at in this article comes from PEP 515: Underscores in Numeric Literals. As the name of the PEP implies, this basically gives you the ability to write long numbers with underscores where the comma normally would be. In other words, 1000000 can now be written as 1_000_000. Let’s take a look at some simple examples:

>>> 1_234_567
1234567
>>>'{:_}'.format(123456789)
'123_456_789'
>>> '{:_}'.format(1234567)
'1_234_567'

The first example just shows how Python interprets a large number with underscores in it. The second example demonstrates that we can now give Python a string formatter, the “_” (underscore), in place of a comma. The results speak for themselves.

The numeric literals that include underscores behave the same way as normal numeric literals when doing calculations:

>>> 120_000 + 30_000
150000
>>> 120_000 - 30_000
90000

The Python documentation and the PEP also mention that you can use the underscores after any base specifier. Here are a couple of examples taken from the PEP and the documentation:

>>> flags = 0b_0011_1111_0100_1110
>>> flags
16206
>>> 0x_FF_FF_FF_FF
4294967295
>>> flags = int('0b_1111_0000', 2)
>>> flags
240

There are some notes about the underscore that need to be mentioned:

  • You can only use one consecutive underscore and it has to be between digits and after any base specifier
  • Leading and trailing underscores are not allowed

This is kind of a fun new feature in Python. While I personally don’t have any use cases for this in my current job, hopefully you will have one at yours.

wxPython Cookbook Artist Interview: Liza Tretyakova

I always put a lot of thought into the covers of my book. For my first book on wxPython, I thought it would be fun to do a cookbook because I already had a lot of recipes on my blog. So I went with the idea of doing a cookbook. For the cover, my first thought was to have some kind of kitchen scene with mice cooks. Then I decided that was too obvious and decided to go with the idea of an Old West cover with cowboy (or cow mice) cooking at a fire.

I asked Liza Tretyakova, my cover artist for wxPython Cookbook, to do a quick interview about herself. Here is what she had to say:

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

My name is Liza Tretyakova, I’m a free-lance illustrator currently working in Moscow.

Education:

  • Moscow State University, Faculty of History of Arts
  • BA(Hons) Illustration, University of Plymouth


I work as an illustrator for about 10 years. I love horses and I used to have a horse. Also I’m interested in archery. I like reading and spending a lot of time with my daughter Yara, who is 7 years old.

What motivated you to be an illustrator versus some other profession?

Since I was a child I have been drawing all the time and it just happened that I started to work as an illustrator, it turned into a profession.

What process do you go through when you are creating a new piece of art?

It is different every time, there is no specific “recipe” 🙂

Do you have any advice for someone who wants to be an illustrator?

You should try to draw every day, the more the better.

Do you have anything else you would like to say?

It was a pleasure working with you!

Thanks so much for doing the interview and for agreeing to be my illustrator for my wxPython Cookbook.

You can see more of Liza’s work on Behance.

Python 201: Intermediate Python FREE until Wednesday!

I decided it would be fun to give my latest book away for free until this Wednesday, Oct 19th. So starting today, you can get Python 201: Intermediate Python free through Gumroad or Leanpub.

If you go with Gumroad, then you will need to use the following offer code: 201free. Note that if you want to receive updates to the book, you will want to create an account and add the book to your library.

Python201_cover20160330_sm-237x300

Book Contest: Win a Copy of Python 201

I have decided to sponsor a contest for my second book, Python 201: Intermediate Python. I will be giving away 3 copies of my eBook bundle (PDF, EPUB and MOBI) and 2 copies of the paperback, which I will ship anywhere in the world. If you haven’t heard of my book, you may want to read about it here.

How You Can Win

To win your copy of this book, all you need to do is come up with a comment below highlighting the reason “why you would like to win this book”.

Duration of the contest & selection of winners

The contest is valid until Friday, Sept 16th at 11:59 p.m. CST, and is open to everyone. Winners will be selected on the basis of their comment posted. The contest will close on 09/17/2016 at 12 a.m. CST.

Python201_cover20160330_sm-237x300

Python 201: A Tutorial on Threads

The threading module was first introduced in Python 1.5.2 as an enhancement of the low-level thread module. The threading module makes working with threads much easier and allows the program to run multiple operations at once.

Note that the threads in Python work best with I/O operations, such as downloading resources from the Internet or reading files and directories on your computer. If you need to do something that will be CPU intensive, then you will want to look at Python’s multiprocessing module instead. The reason for this is that Python has the Global Interpreter Lock (GIL) that basically makes all threads run inside of one master thread. Because of this, when you go to run multiple CPU intensive operations with threads, you may find that it actually runs slower. So we will be focusing on what threads do best: I/O operations!


Intro to Threads

A thread let’s you run a piece of long running code as if it were a separate program. It’s kind of like calling subprocess except that you are calling a function or class instead of a separate program. I always find it helpful to look at a concrete example. Let’s take a look at something that’s really simple:

import threading
 
 
def doubler(number):
    """
    A function that can be used by a thread
    """
    print(threading.currentThread().getName() + '\n')
    print(number * 2)
    print()
 
 
if __name__ == '__main__':
    for i in range(5):
        my_thread = threading.Thread(target=doubler, args=(i,))
        my_thread.start()

Continue reading Python 201: A Tutorial on Threads

Python 201 Writing Update: Only 4 Chapters to go!

I finished up section #4 earlier this week which brings the book up to 26 chapters and a little over 200 pages. I have four more chapters planned and then a couple of updates to previous chapters. My goal is to have the book ready for proofing at the end of the month. Then I’ll create a sample print of the book and check it over for errors.

If anyone has been reading the book and found any errors, please let me know. I’ll be finalizing the chapters in mid-August or so and would like them to be as good as they can be before then.

Thanks so much for your support!
Mike

P.S. If you’d like to purchase the early version of the book, you can do at Gumroad or Leanpub

Python 201: An Intro to mock

The unittest module now includes a mock submodule as of Python 3.3. It will allow you to replace portions of the system that you are testing with mock objects as well as make assertions about how they were used. A mock object is used for simulating system resources that aren’t available in your test environment. In other words, you will find times when you want to test some part of your code in isolation from the rest of it or you will need to test some code in isolation from outside services.

Note that if you have a version of Python prior to Python 3, you can download the Mock library and get the same functionality.

Let’s think about why you might want to use mock. One good example is if your application is tied to some kind of third party service, such as Twitter or Facebook. If your application’s test suite goes out and retweets a bunch of items or “likes” a bunch of posts every time its run, then that is probably undesirable behavior since it will be doing that every time the test is run. Another example might be if you had designed a tool for making updates to your database tables easier. Each time the test runs, it will do some updates on the same records every time and could wipe out valuable data.

Instead of doing any of those things, you can use unittest’s mock. It will allow you to mock and stub out those kinds of side-effects so you don’t have to worry about them. Instead of interacting with the third party resources, you will be running your test against a dummy API that matches those resources. The piece that you care about the most is that your application is calling the functions it’s supposed to. You probably don’t care as much if the API itself actually executes. Of course, there are times when you will want to do an end-to-end test that does actually execute the API, but those tests don’t need mocks!

Continue reading Python 201: An Intro to mock

Python 3 Testing: An Intro to unittest

The unittest module is actually a testing framework that was originally inspired by JUnit. It currently supports test automation, the sharing of setup and shutdown code, aggregating tests into collections and the independence of tests from the reporting framework.

The unittest frameworks supports the following concepts:

  • Test Fixture – A fixture is what is used to setup a test so it can be run and also tears down when the test is finished. For example, you might need to create a temporary database before the test can be run and destroy it once the test finishes.
  • Test Case – The test case is your actual test. It will typically check (or assert) that a specific response comes from a specific set of inputs. The unittest frameworks provides a base class called **TestCase** that you can use to create new test cases.
  • Test Suite – The test suite is a collection of test cases, test suites or both.
  • Test Runner – A runner is what controls or orchestrates the running of the tests or suites. It will also provide the outcome to the user (i.e. did they pass or fail). A runner can use a graphical user interface or be a simple text interface.

Continue reading Python 3 Testing: An Intro to unittest