So you want to Python

Last week I gave a talk on an overview of Python.  The talk was focused on being a very brief introduction into Python.  The talk assumed that the audience had little to no Python experience, but had a solid background in another programming language (in this case everybody had solid C# experience).

This is a rehash of that presentation.

Slide1

Introductory Slides

Slide4

The main point here is that Python is more than just what you download when you go to Python.org. At the core Python is just a programming language spec. A whole community and ecosystem has evolved around that spec.  The language itself brings with it a core set of values that are embraced by the community.  These values are summed up in the ‘Zen of Python’.


"
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"

Slide4

To reiterate: at the core Python is just a language spec.  Because of this there are more than just one implementation of Python. 

  • CPython written in C and is the reference implementation of Python. This is what is downloaded from Python.org.
    • Note: Version 3 is NOT backwards compatible with version 2. Some version 3 features were back ported, but they are still different. As of this writing my recommendation for getting started in Python would be to download the latest 2.7 version.
  • IronPython written in C#. Targets the Microsoft CLR.  It was built to showcases the DLR.
  • Jython written in Java. Targets JVM.
  • PyPy written in RPython. RPython a subset of Python, but specializes in writing JIT compiled interpreters. This is the implementation that intrigues me the most.
  • Others: http://wiki.python.org/moin/PythonImplementations

Slide7

The talk didn’t go into great depths about setting up a development environment or best practices while developing in Python (for a great piece on that visit: http://mirnazim.org/writings/python-ecosystem-introduction/).  However I wanted to mention pip,virtualenv, and setuptools.  These tools will greatly reduce some frustration when dealing with different Python environments and different libraries available.

Language Overview

Basic Types


i = 1 # integer
l = 777777L # long
f = 99.9 # float
s1 = 'Hello' # string
s2 = "I'm a string" # string
b = True # boolean
n = None # null

These are the basic types of Python. Notice how to declare a variable, you just set it equal to something and the interpreter figures out what type is. The only other thing going on in the code above is you can see how a comment is written in Python.

Containers


# tuple
t1 = (1,2.0,'hi')
t2 = tuple(['iterable'])

# list
l1 = [5, 4.0, 'bye']
l2 = list('iterable')

# dictionary
d1 = {'one': 1, 'two': 2, 3: 'three'}
d2 = dict(four=4, five=5.5)

# set
sl = set(['iterable'])

Containers are types that let you store other items in them. The 4 containers tuple,list,dictionary and set are 4 commonly used containers in Python. Python has a lot of support for manipulating containers, and passing them around. They are central to many Python programs.

  • Tuple – An immutable sequence. Items are stored in order, but the sequence cannot be changed once initialized.
  • List – A mutable sequence. Like a tuple a list’s items are stored inorder, but items can be added, removed, sorted, etc.
  • Dictionary – A key/value pair. The key must be unique, but is not limited to what type it is. The only requirement is that the key is hashable. A dictionary’s items are not stored in order, they are stored in order of the hash of the key in order to make lookups faster.
  • Set – A hashed collection of items. Think of sets as an unordered list.

Operators

  • Math: + – / * // ** %
  • Bitwise: & ^ ~ | << >>
  • Sequence: + * [:] [] in
  • Comparison: < > != == <= >= is not and or

A lot of the operators should be familiar to users of other languages, particularly languages with C like syntax. I’ll just call a few out. The // operator is floor division (not a comment). The ** operator is the power operator (2**3 means 2 to the power of 3). The [:] operator is the slice operator. I am not going to go much into slices, but they are an important concept in Python. Basically a slice is a section of a sequence. Numbers can be used in the slice operator to specify what section of a sequence required.

Conditionals


# if-elif-else
x = 1
y = 0
if x < y: print('weird') elif x > y:
print('duh')
else:
print('odd')

# Expression
x = 1 if True else 100

The only real conditional construct in Python the ‘if’ construct. It can be used as a statement or as an expression. Using it a statement we can see how to construct a code block in Python. A code block follows a colon and must be indented using the same indentation for the whole block. This is what it meant when people say whitespace matters in Python. It helps to keep the source code looking clean.

Loops


# A while loop
while True:
print('Hello')

# for loops
for x in range(10):
print x
for name in ('Chris', 'Mike', 'Joe'):
print ('Hello {0}'.format(name))
for name, age in [('Chris', 'old'), ('Clayton', 3), ('Ashton', 1)]:
print ("{0} is {1}".format(name, age))

Two basic loop constructs. A while loop acts pretty much like it does in many other languages, while condition do code block. For loops are more powerful in Python than a lot languages with a for loop rooted in C history. During each iteration of the loop the loop variables are initialized to the next item. Notice how there can be multiple loop variables. Also notice how a variable is not restricted to a type. The type can change on each iteration as long as it make sense to the code block.

Functions


# Regular Function
def my_fun(name='Nobody'):
return 'Howdy {0}'.format(name)

# returns 'Howdy Nobody'
my_fun()

# Functions are are first class
vfun = my_fun

# Returns 'Howdy Function'
vfun('Function')

# Lambda Function Note: cannot contain statements (i.e. print;for;etc)
lfun = lambda greeting, name: '{0} {1}'.format(greeting, name)

# Funtional functions
map(vfun, ['A', 'B']) # returns ['Howdy A', 'Howdy B']
filter(lambda big: big > 10, (100, 1)) # returns (100,)
reduce(lfun, ('Hi', 'Chris', 'H')) # returns 'Hi Chris H'

Functions are the smallest building block for holding code in Python. They are also first class, which mean they can be set to variables and be passed around. This allows for some basic functional style programming in Python. Python has lambdas, however they are not full functions. Typically a lambda is great for a simple one liner, however anything more complex a function can be used. Also note that functions can be declared in functions, this again makes lambda’s a little less desirable then they can be in other languages.

Code Organization

Slide14

Like what was mentioned before functions are the smallest level of code building blocks. Functions can live inside functions, modules, classes, and packages. Modules can also contain classes; packages can contain modules and classes. In terms of actually implementing the organization the easiest way to think about it is a function is a function, a class is a class a module is the file (file name is the module name) and a package is the directory name. There is a special file __init__.py that allows for more control over the package (and technically __init__.py is required to exist inside a package, but may be empty). They organization can be more complex, but doesn’t need to be.

Cool Stuff: Generators


def get_odds(nums):
for num in nums:
if num % 2 != 0:
yield num

for odd in get_odds(range(10)):
print(odd)

Generators are a way to control what happens in each iteration of a loop. Those of you familier with C#: think IEnumerable. On each iteration of the loop the generator will be called and the next object will be returned. One key to thinking about generators is that code is not called until runtime.

Cool Stuff: Decorators


from datetime import datetime

class logit:
def __init__ (self, function):
self.f = function

def __call__ (self, *args):
print("+++ {0} @ {1}".format(self.f.__name__, datetime.now()))
self.f(*args)
print("--- {0} @ {1}".format(self.f.__name__, datetime.now()))

@logit # <--- This is the decorator def add(nums): s = 0 for num in nums: s = s + num print (s) return s add(range(50000)) # output: # +++ add @ 2012-06-08 14:33:43.687000 # 1249975000 # --- add @ 2012-06-08 14:33:43.700000
A whole blog series could be written about decorators. The one shown here was chosen to show some of the power of decorators, without all the complexity that could come with implementing your own decorator. The simplest way to think of a decorator would be a function that gets called before the function that it decorates is called. The decorator itself is actually in charge of calling the decorated function. This allows decorators to do things before the decorated function is called, after the decorated functions is called, or even not call the decorated function at all (say you wanted a function to only run on Monday's, you can do that with decorators).

Sample Program - Snake game

In order to illustrate some of the power of Python I created a simple game and put the source online. Feel free to browse the source and drop me a line with any questions/comments. A lot of what was covered in the presentation is available in the game.

https://bitbucket.org/sirchristian/snakes

image

Closing

This was meant to just whet your palate when it comes to Python development. Python has many more neat features that I encourage everybody to check out. Go download your choice of Python and start developing!

Reference

Leave a Reply