python.md
April 2, 2014 ยท View on GitHub
Python Cheat Sheet
This is not an introduction to Python. For that, see the Python tutorial or the Python module index. Instead, this lists some tips and pointers that will prove useful when working on your language.
Lists
Lists will comprise our ASTs, so you'll need lists pretty early on. The tutorial page on lists should prove useful.
Dictionaries
We'll be using dictionaries when representing the program environments.
-
Remember that dicts are mutable in Python. Use the
copyfunction when a copy is needed. -
To update a dictionary with values from another, use
update. -
You will find yourself needing to make a dictionary from a list of keys and a list of values. To do so, combine the
dictandzipfunctions like this:>>> dict(zip(["foo", "bar"], [1, 2])) {'foo': 1, 'bar': 2}
Read more about dicts in the documentation.
Strings
-
Strings works in many ways like lists. Thus, you can substring using indices:
>>> "hello world"[6:] 'world' -
Remove unwanted whitespace using
str.strip(). -
It is also useful to know about how to do string interpolation in Python.
>>> "Hey, %s language!" % "cool" 'Hey, cool language!' >>> "%d bottles of %s on the wall" % (99, "beer") '99 bottles of beer on the wall' >>> "%(num)s bottles of %(what)s on the %(where)s, %(num)d bottles of %(what)s" \ ... % {"num": 99, "what": "beer", "where": "wall"} '99 bottles of beer on the wall, 99 bottles of beer'
Classes
When defining a class, all methods take a special argument self as the first argument. The __init__ method works as constructor for the class.
class Knight:
def __init__(self, sound):
self.sound = sound
def speak(self):
print self.sound
You don't provide the self when creating instances or calling methods:
>>> knight = Knight("ni")
>>> knight.speak()
ni
Default argument values
One thing it is easy to be bitten by is the way Python handles default function argument values. These are members of the function itself, and not "reset" every time the function is called.
>>> def function(data=[]):
... data.append(1)
... return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]
Beware this when you implement the Environment class.