Python 201 is Now an Online Course

My second book, Python 201: Intermediate Python, was just released as an online course over at Educative. I also have Python 101 on there as well. Educative is a pretty new educational website. It’s kind of like Code Academy except that they usually charge for access to all their courses.

Note: This is NOT a video course!

Anyway, they were kind enough to provide me with a 50% off coupon to share with anyone on Reddit. Here it is: au-py201-50. Note: This coupon code is only good for 1 week.

If you haven’t heard of my second book, then you’ll find a really good table of contents and some free content on Educative. You can also see the book’s table of contents on Leanpub here: https://leanpub.com/python201/

PyDev of the Week: Dan Bader

This week we welcome Dan Bader (@dbader_org) as our PyDev of the Week. Dan does a weekly Python Tricks newsletter / blog that’s a fun read. He has also authored a Python Tricks book. I always like checking out my interviewee’s Github page to see what they enjoy coding or writing about, so I encourage you to check that out as well. Let’s take a few moments to learn more about Dan!

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

Hey everyone :wave: My name is Dan Bader and I’m a complete Python nut. I’ve been obsessed with programming ever since I managed to convince my parents to buy me a dusty old Commodore 64 from the classifieds in a local newspaper. And my love for writing code hasn’t diminished since then.

Eventually I got a bachelor’s and a master’s degree in Computer Science. I worked in full-time positions for a few years and today I’m an independent software developer and consultant.

I was born and grew up in Germany but then later moved to Canada. I love both countries—and fortunately I mostly work remotely these days so I get to visit each one a fair bit. I’m glad I found a partner who’s willing to put up with these antics :slightly_smiling_face:

In terms of hobbies I like working out at the gym, cooking vegetarian food (buying my first proper cast-iron wok in Vancouver’s chinatown changed my life, haha), and going on hikes. I also read a lot. In general I found what makes me the happiest is building stuff. So I try and optimize for that. Every now and then I play some guitar to relax.

Continue reading PyDev of the Week: Dan Bader

Python 101: Equality vs Identity

People who are new to the Python programming language can get a bit confused about the difference between “==” (equality) and Python’s keyword “is” (identity). I have even seen experienced programmers who will find the difference subtle enough that they will introduce logic errors in their code do to a misunderstanding between the two. In this article, we will look at this interesting topic.


Equality in Python

Many programming languages have the concept of equality and several use the double equals sign (“==”) to designate this concept. Let;s take a look at equality in action:

>>> num = 1
>>> num_two = num
>>> num == num_two
True

Here we create a variable that we call num and assign it to the integer 1. Next we create a second variable called num_two and assign it to the value of num. Finally we ask Python if num and num_two are equal. In this case, Python tells us that this expression is True.

Another way to think of equality is that we are asking Python if two variables contain the same thing. In the example above, they both contain the integer 1. Let’s see what happens when we create two lists with the same values:

>>> list_one = [1, 2, 3]
>>> list_two = [1, 2, 3]
>>> list_one == list_two
True

This worked out the way we expected. Continue reading Python 101: Equality vs Identity

PyDev of the Week: Victor Stinner

This week we welcome Victor Stinner as our PyDev of the Week! Victor is quite active in the Python community and is a core Python developer. You can see some of his contributions here. He is the author of eight accepted PEPs which you can also read about at the previous link. If you’re interested in seeing what else Victor has been up to, then I highly recommend checking Github and ReadTheDocs. Victor also has put together some interesting benchmarks for CPython and about FASTCALL optimization. You might also want to check out his latest talk about Python benchmarks here: https://fosdem.org/2017/schedule/event/python_stable_benchmark/

Now let’s spend some time getting to know Victor better!

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

Hi, my name is Victor Stinner, I’m working for Red Hat on OpenStack, and I’m a CPython core developer since 2010.

I am an engineer from the engineer school Université de Technologie de Belfort-Montbéliard (UTBM), France. When I don’t hack CPython, I play with my two little cute daughters 🙂

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

I was always programming. I tried a wide range of programming languages from the lowest level Intel x86 assembler to high level languages like Javascript and BASIC. Even if I now really enjoy writing C code for best performances, Python fits better my requirements for my daily job. Since it’s easy to write Python code, and I’m not annoyed by memory management or analyzing crashes, I use the “free” time to write more unit tests, take care of the coding
style, and all tiny stuffs which make a software a “good software”.

After 10 years of professional programming, I can now say that I spent more time on reading “old” code and fixing old complex corner case, than writing new code from scratch. Having an extensible test suite makes me more cool. Having to work under pressure without straps is likely to lead to burnout, or more simply to quit a job.

Continue reading PyDev of the Week: Victor Stinner

Python 3 – Unpacking Generalizations

Python 3.5 added more support for Unpacking Generalizations in PEP 448. According to the PEP, it added extended usages of the * iterable unpacking operator and ** dictionary unpacking operators to allow unpacking in more positions, an arbitrary number of times, and in additional circumstances. What this means is that we can now make calls to functions with an arbitrary number of unpackings. Let’s take a look at a dict() example:

>>> my_dict = {'1':'one', '2':'two'}
>>> dict(**my_dict, w=6)
{'1': 'one', '2': 'two', 'w': 6}
>>> dict(**my_dict, w='three', **{'4':'four'})
{'1': 'one', '2': 'two', 'w': 'three', '4': 'four'}

Interestingly, if the keys are something other then strings, the unpacking doesn’t work:

>>> my_dict = {1:'one', 2:'two'}
>>> dict(**my_dict)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    dict(**my_dict)
TypeError: keyword arguments must be strings

Update: One of my readers was quick to point out that the reason this doesn’t work is because I was trying to unpack into a function call (i.e. dict()). If I had done the unpacking using just dict syntax, the integer keys would have worked fine. Here’s what I’m talking about:

>>> {**{1: 'one', 2:'two'}, 3:'three'}
{1: 'one', 2: 'two', 3: 'three'}

One other interesting wrinkle to dict unpacking is that later values will always override earlier ones. There’s a good example in the PEP that demonstrates this:

>>> {**{'x': 2}, 'x': 1}
{'x': 1}

I thought that was pretty neat. You can do the same sort of thing with ChainMap from the collections module, but this is quite a bit simpler.

However this new unpacking also works for tuples and lists. Let’s try combining some items of different types into one list:

>>> my_tuple = (11, 12, 45)
>>> my_list = ['something', 'or', 'other']
>>> my_range = range(5)
>>> combo = [*my_tuple, *my_list, *my_range]
>>> combo
[11, 12, 45, 'something', 'or', 'other', 0, 1, 2, 3, 4]

Before this unpacking change, you would have had do something like this:

>>> combo = list(my_tuple) + list(my_list) + list(my_range)
[11, 12, 45, 'something', 'or', 'other', 0, 1, 2, 3, 4]

I think the new syntax is actually quite handy for these kinds of circumstances. I’ve actually run into this a time or two in Python 2 where this new enhancement would have been quite useful.


Wrapping Up

There are lots of other examples in PEP 448 that are quite interesting to read about and try in Python’s interpreter. I highly recommend checking it out and giving this feature a try. I am hoping to start using some of these features in my new code whenever we finally move to Python 3.

PyDev of the Week: Petr Viktorin

This week our PyDev of the Week is Petr Viktorin (@EnCuKou). Petr is the author of PEP 489 — Multi-phase extension module initialization and teaches Python for the local PyLadies in Czech Republic. You can some of what he’s up to via his Github page or on his website. Let’s take some time to get to know Petr better!

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

Sure!

I’m a Python programmer from Brno, Czech Republic. I studied at the Brno University of Technology, and for my master’s I switched to the University of Eastern Finland.

When I’m not programming, I enjoy playing board games with my friends, and sometimes go to an orienteering race (without much success).

Why did you start using Python?

At the university, I did coursework in languages like C, Java, and Lisp, but then I found Python and got hooked. It fit the way I think about programs, abstracted away most of the boring stuff, and makes it easy to keep the code understandable.

After I returned home from the university, I found a community that was starting to form around the language, and that’s probably what keeps me around the language now.

Continue reading PyDev of the Week: Petr Viktorin

Python’s New secrets Module

Python 3.6 added a new module called secrets that is designed “to provide an obvious way to reliably generate cryptographically strong pseudo-random values suitable for managing secrets, such as account authentication, tokens, and similar”. Python’s random module was never designed for cryptographic use but for modeling and simulation. Of course, you could always use the urandom() function from Python’s os module:

>>> import os
>>> os.urandom(8)
'\x9c\xc2WCzS\x95\xc8'

But now that we have the secrets module, we can create our own “cryptographically strong pseudo-random values”. Here’s a simple example:

>>> import secrets
>>> import string
>>> characters = string.ascii_letters + string.digits
>>> bad_password = ''.join(secrets.choice(characters) for i in range(8))
>>> bad_password
'SRvM54Z1'

In this example, we import the secrets and the string modules. Next we create a string of uppercase letters and integers. Finally we use the secrets module’s choice() method to choose characters randomly to generate a bad password. The reason I am calling this a bad password is because we aren’t adding symbols to the password. This is actually a fairly decent one compared with what a lot of people use. One of my readers pointed out that another reason this could be considered bad is that the user would probably just write it down on a piece of paper. While that may be true, using dictionary words is typically strongly discouraged so you should learn to use passwords like this or invest in a secure password manager.

Continue reading Python’s New secrets Module

What’s New in Python: Asynchronous Comprehensions / Generators

Python 3.6 added the ability to create Asynchronous Comprehensions and Asynchronous Generators. You can read about asynchronous comprehension in PEP 530 while the asynchronous generators are described in PEP 525. The documentation states that you can now create asynchronous list, set and dict comprehensions and generator expressions. Their example looks like this:

result = [i async for i in aiter() if i % 2]

Basically you just need to add Python’s new async keyword into your expression and call a callable that has implemented __aiter__. Trying to follow this syntax will actually result in a SyntaxError though:

>>> result = [i async for i in range(100) if i % 2]
  File "<stdin>", line 1
    result = [i async for i in range(100) if i % 2]
                    ^
SyntaxError: invalid syntax
</stdin>

Continue reading What’s New in Python: Asynchronous Comprehensions / Generators

PyDev of the Week: Lukasz Langa

This week we welcome Łukasz Langa (@llanga) as our PyDev of the Week! Łukasz is the author of PEP 443 — Single-dispatch generic functions. He also authors an interesting blog, although it’s not just a programming blog. You can see what Łukasz has been up to over on Github. Let’s take a few moments to get to know him better!

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

My first name is Łukasz which is an endless source of Unicode joy. I am a committer to Python since 2010, started out as a maintainer for configparser, nowadays working on the type hinting side of things. I like analog synthesizers, bicycles, and the Fallout game series. In my free time I’m helping Facebook embrace Python 3.

Why did you start using Python?

This is a bit embarrassing. It was Autumn 2004, I was studying Computing Science at Poznan University of Technology in Poland. I had trouble with some courses I took, namely Linear Algebra. A friend showed me some scripts he wrote in Ruby and some linear algebra library to check his results when solving homework assignments. I badly needed some reassurance so I got excited about this. Sadly, for some reason Ruby refused to install on my Windows XP box at the time.

As a test was scheduled for the very next day, I started looking for alternatives. I literally typed “ruby alternative” in Google and found Python that way. This installed cleanly and I quickly found a functional linalg library replacement. I can’t remember what it was anymore, this was before NumPy was a thing! Either way, I got hooked.

Continue reading PyDev of the Week: Lukasz Langa

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