Category Archives: Python

Is related to the Python Programming language in some way

PyDev of the Week: Roman Sirokov

This week we welcome Roman Sirokov as our PyDev of the Week! He is the author of pywebview, which is a cross-platform lightweight native wrapper around a web view component. You can basically create a desktop user interface using web technologies and frameworks. He is quite active on Github where you can see all the projects he is involved with. Let’s take a few moments to learn more about our fellow Pythonista!

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

I am a software engineer from Helsinki, Finland. I currently work for Siili Solutions as a full-stack developer doing various client projects.

I have two master degrees, one in computer science from Aalto University and the second one in bioinformatics from University of Helsinki. The first degree was about graduating and the second one about actually wanting to learn something.

I have traveled quite a bit and the longest I have spent on the road was nine months. On one occasion I cycled about 3000km around Baltic Sea during a very rainy summer. I am an avid cross-country skier and try to get as much as skiing as possible with very little snow we get nowadays. I practice ashtanga yoga and vipassana meditation too and try to attend a vipassana retreat once a year. Other than that I dj mostly cosmic music and try to keep my cats entertained. Some of my mixes can be found here.

Continue reading PyDev of the Week: Roman Sirokov

Python 101 Online Course is FREE for 48 Hours!

My Python 101 online course will be completely FREE for the next 48 hours on Educative’s website. Be sure to go get yourself a copy.

It is based on my Python 101 book. When you get it from Educative, it will be yours to keep for life. Note that this is an interactive online course, not a video course. If you enjoy the Python 101 online course, you can get my second online course, Python 201 for 50% off just by using the following coupon: au-promo-py201.

Links:

  • Python 101 Online course (FREE for 48 Hours)
  • Python 201 Online course (50% off with au-promo-py201 coupon

You can also get my eBooks for 50% off the suggested price with the following links:

PyDev of the Week: Paul Moore

This week we welcome Paul Moore as our PyDev of the Week! Paul is a core developer of pip, the defacto method of installing packages in Python as well as a core developer of Python itself. You can get a glimpse of some of the projects that Paul is involved with on his Github profile. Let’s spend some time getting to know Paul better!

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

I was born in Liverpool, England, and (apart from a few years in Cambridge studying maths at university) I’ve lived in the north west of England all my life. When I was at school, my passion was for maths, which led to an interest in programming and computers. My first computer was a Sinclair ZX-81 and I learned Z80 assembler from a disassembly of the complete OS of that machine – not something I’d ever try these days! I quickly moved onto the BBC micro and then the Acorn Archimedes, until I finally joined the mainstream in about 1995 when I got my first PC. Although I’ve always been interested in Unix, I never really used it at home, so I’ve pretty much always been a Windows user (which has its frustrations, but is also much more fun as you get the chance to port stuff that the Unix people take for granted :-)).

In the past I’ve contributed to a lot of open source projects – vim (I wrote the original OLE and Python interfaces), the Boost C++ libraries, some long-gone Windows utility libraries – and ported a lot of Unix programs to Windows (I had my own ports of many of the GNU utilities). These have mostly died down now, and I focus mainly on Python.

In my working life, I work for a software consultancy doing Oracle support. While there’s not much official use of Python involved, I’ve always used it as much as possible for background scripts and personal utilities. And these days it’s nice to see it appearing more and more as a “mainstream” language – it’s popping up in all sorts of unexpected places these days.

Outside of computing I like to spend time with my family (I’m married and I have a son and daughter, both at university/college), as well as playing music (guitar and piano), playing boardgames and reading/watching videos. I used to practice Ju Jitsu, but haven’t had time in a few years now (advancing age may also have been a factor!)

Continue reading PyDev of the Week: Paul Moore

Python 101 – An Intro to IDLE

Python comes with its own code editor: IDLE (Integreted Development and Learning Environment). There is some lore that the name for IDLE comes from Eric Idle, an actor in Monty Python. An IDE is an editor for programmers that provides color highlighting of key words in the language, auto-complete, an “experimental” debugger and lots of other fun things. You can find an IDE for most popular languages and a number of IDEs will work with multiple languages. IDLE is kind of a lite IDE, but it does have all those items mentioned. It allows the programmer to write Python and debug their code quite easily. The reason I call it “lite” is the debugger is very basic and it’s missing other features that programmers who have a background using products like Visual Studio will miss. You might also like to know that IDLE was created using Tkinter, a Python GUI toolkit that comes with Python.

Continue reading Python 101 – An Intro to IDLE

Python 101: All About Dictionaries

The Python programming language has several built-in types that it supports. One of my favorites is the dictionary. A dictionary is a mapping object maps hashable values to arbitrary objects (source). Other languages call dictionaries “hash tables”. They are mutable objects that you can change whenever you want to, unlike tuples. A dictionary’s keys must be hashable or immutable, which means that you cannot use a list or another dictionary as a key. Note that dictionaries before Python 3.6 are not ordered. In Python 3.6, they changed the dict’s implementation so that it is now ordered, although there is a warning mentioned that you should not rely on it being ordered. What this means is that when you iterate over a dictionary, you may not extract the values in the same order that you inserted them except in Python 3.6 and potentially future versions of Python.

In this article, we will take some time learning about some of the many things you can do with a dictionary.


Creating Dictionaries

A dictionary is a key:value pair. In Python, these key:value pairs are enclosed inside of curly braces with commas between each pair. Creating dictionaries in Python is really easy. Here are the three ways to create a dictionary:

>>> my_dict = {}
>>> my_other_dict = dict()
>>> my_other_other_dict = {1: 'one', 2: 'two', 3: 'three'}

In the first example, we create an empty dictionary by just assigning our variable to a pair of empty curly braces. You can also create a dictionary object by calling Python’s built-in dict() keyword. I have seen some people mention that calling dict() is slightly slower than just doing the assignment operator. The last example shows how to create a dictionary with some predefined key:value pairs. You can have dictionaries that contain mappings of various types, including mapping to functions or objects. You can also nest dictionaries and lists inside your dictionaries!

Continue reading Python 101: All About Dictionaries

How to Run Python Tests “Continuously” While Coding

Last week I was doing some Test Driven Development training and overheard someone mention another programming language that had a test runner that you could set up to watch your project directory and run your tests when the files changed. I thought that was a neat idea. I also thought I could easily write my own Python script to do the same thing. Here’s a pretty rough version:

import argparse
import os
import subprocess
import time
 
 
def get_args():
    parser = argparse.ArgumentParser(
        description="A File Watcher that executes the specified tests"
        )
    parser.add_argument('--tests', action='store', required=True,
                        help='The path to the test file to run')
    parser.add_argument('--project', action='store', required=False,
                        help='The folder where the project files are')
    return parser.parse_args()
 
 
def watcher(test_path, project_path=None):
    if not project_path:
        project_path = os.path.dirname(test_path)
 
    f_dict = {}
 
    while True:
        files = os.listdir(project_path)
        for f in files:
            full_path = os.path.join(project_path, f)
            mod_time = os.stat(full_path).st_mtime
            if full_path not in f_dict:
                f_dict[full_path] = mod_time
            elif mod_time != f_dict[full_path]:
                # Run the tests
                cmd = ['python', test_path]
                subprocess.call(cmd)
                print('-' * 70)
                f_dict[full_path] = mod_time
 
        time.sleep(1)
 
 
def main():
    args = get_args()
    w = watcher(args.tests, args.project)
 
if __name__ == '__main__':
    main()

To run this script, you would need to do something like this:


python watcher.py --test ~/path/to/tests.py --project ~/project/path

Continue reading How to Run Python Tests “Continuously” While Coding

PyDev of the Week: Luke Plant

This week we welcome Luke Plant as our PyDev of the Week. Luke is one of the core developers of Django, a very popular Python web framework. Luke writes a blog with many articles about Django. If you’d like to see some of Luke’s contributions, then you will want to wander over to his Github profile soon. Let’s take a few minutes to get to know Luke better!

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

I grew up in England, and currently live in Turkey with my wife and son, and a second on the way! [He means a second child, not a second wife – The Wife]. At the moment my dominating ‘hobby’ is learning Turkish, which is pretty tough work, but very rewarding too. I also enjoy playing the guitar (though not to any high standard!).

Regarding learning to program, I’ve been mainly self-taught: as a kid it was the 8-bit, 64K Oric Atmos that my dad bought (which was brilliant – there was an invaluable Advanced Users Manual that told you pretty much everything about it, including a complete ROM disassembly listing), then later messing around with VBA and Microsoft Office. My dad’s interest in messing around with computers meant that we were one of the first families I knew to be regularly using email and the web.

I went to university to study Physics/Natural Sciences, but in my first week there, my career in science was derailed when a friend decided to install Linux on my Windows machine before I even knew what he was doing. Thankfully he left Windows on there too, rather than just wiping my hard drive! But that introduced me to the Open Source world, which re-kindled my previous interest in programming, and both the fun and the philosophy behind Open Source programming have been a major influence on me since. Thankfully, although I was studying science not programming, I was able to do a fair number of programming related projects – one of which I recently had fun re-implementing using IPython Notebook.

Continue reading PyDev of the Week: Luke Plant

Python – How to tell if a Function Has Been Called

Last year I ran into a situation where I needed to know if a function had been called. Basically we were trying to prevent shutting down a Twisted event loop twice or starting two of them. Anyway, in my research I stumbled across a fun post on StackOverflow that showed a couple of ways to do this.

The first made use of the fact that everything in Python is an object, including the function itself. Let’s take a look at a simple example:

def self_aware_function(a, b):
    self_aware_function.has_been_called = True
    return a + b
 
if __name__ == '__main__':
    self_aware_function.has_been_called = False
 
    for i in range(2):
        if self_aware_function.has_been_called:
            print('function already called')
        else:
            print('function not called')
 
        self_aware_function(1, 2)

In this example, we create an attribute on the function that we named has_been_called. We set it to True when the function is called. When you start your program, you will want to initialize that attribute to False, which we do above. Then we use a for loop to loop twice. The first time through it will check if the function has been called. Since it hasn’t, you will see it fall to the else statement. Now that we called the function, the second time through the loop the first part of the if statement executes.

Continue reading Python – How to tell if a Function Has Been Called