Difference between revisions of "Python notes"

From Noah.org
Jump to navigationJump to search
Line 40: Line 40:
 
Other libraries to consider: [http://library.gnome.org/devel/gtk/ GTK+] used by Gnome; [http://trolltech.com/products/ Qt] used by KDE; [http://pygame.seul.org/news.html Pygame wrapper on SDL].
 
Other libraries to consider: [http://library.gnome.org/devel/gtk/ GTK+] used by Gnome; [http://trolltech.com/products/ Qt] used by KDE; [http://pygame.seul.org/news.html Pygame wrapper on SDL].
  
== hashlib versus sha (python2.5 vs. python2.4) ==
+
== hashlib versus sha (python2.4 vs. python2.5 vs. python3.0) ==
  
 
Python 2.4:
 
Python 2.4:
  
 
<pre>
 
<pre>
import sha; sha.new('password').hexdigest()
+
import sha
 +
p = 'password'
 +
sha.new(p).hexdigest()
 
</pre>
 
</pre>
  
Line 51: Line 53:
  
 
<pre>
 
<pre>
import hashlib; hashlib.sha1('password').hexdigest()
+
import hashlib
 +
p = 'password'
 +
hashlib.sha1(p).hexdigest()
 +
</pre>
 +
 
 +
Python 3.0:
 +
 
 +
<pre>
 +
import hashlib
 +
p = 'password'
 +
hashlib.sha1(bytes(p,'utf-8')).hexdigest()
 
</pre>
 
</pre>
  

Revision as of 05:47, 31 December 2008

Pexpect

I loved Expect, but I hated TCL, so I wrote this 100% pure Python module that does the same thing. Click here for more details:

Pexpect -- An Expect-like module in pure Python

Free Python software

You can find other free software I wrote (mostly in Python) here: Free Software

Python Style

PEP-8 gives the recommended style for Python code. It isn't very strict and none of that mixed-case stuff they do in Java: http://www.python.org/dev/peps/pep-0008/

A short summary:

Class Names
class names use the CapWords convention. Classes for internal use have a leading underscore in addition.
Function Names
function names should be lowercase, with words separated by underscores as necessary to improve readability.
Line Length
limit all lines to a maximum of 79 characters.
Indentation
use 4 spaces per indentation level. Avoid hard tabs.
Encoding
UTF-8 is preferred over Latin-1.

.vimrc for Python

I like Vim. This is how I set my .vimrc file.

This adds sensible tab settings for Python. It also defines simple folding. I never liked the built-in indent folding for Python because it folds too much -- every indent becomes a fold! For code folding I just want to see class names and method names. I don't need every single nested loop folded many levels deep... In this .vimrc see the section on "folding using /search/ pattern". This maps the normal mode key sequence, 'zff' to set the search pattern to find all class and method names. This also maps '\z' to refold every search pattern. The neat thing is that this pattern also works on PHP code! The '\z' mapping is also handy for editing other documents.

Python Cookbook

I have a few recipes on ActiveState's fun and useful Python cookbook.

GUI toolkits

I hope tkinter will be deprecated someday. I think wxPython is the best alternative at the moment: http://wxpython.org/quotes.php which is a Python interface to wxWidgets.

Other libraries to consider: GTK+ used by Gnome; Qt used by KDE; Pygame wrapper on SDL.

hashlib versus sha (python2.4 vs. python2.5 vs. python3.0)

Python 2.4:

import sha
p = 'password'
sha.new(p).hexdigest()

Python 2.5:

import hashlib
p = 'password'
hashlib.sha1(p).hexdigest()

Python 3.0:

import hashlib
p = 'password'
hashlib.sha1(bytes(p,'utf-8')).hexdigest()

Parse Boolean strings

This will convert boolean strings into Boolean types. This is useful for parsing conf files and the like. This will handle strings like "yes", "1", "true", "no", "false", "0" with any sort of capitalization and whitespace padding. It will raise a ValueError if the string cannot be parsed.

def ParseBoolean (b):
    # Handle case where b is already a Boolean type.
    if b == False or b == True:
        return b
    b = b.strip()
    if len(b) < 1:
        raise ValueError ('Cannot parse empty string into boolean.')
    b = b[0].lower()
    if b == 't' or b == 'y' or b == '1':
        return True
    if b == 'f' or b == 'n' or b == '0':
        return False
    raise ValueError ('Cannot parse string into boolean.')

WTF?

This will test for primality with a regular expression. No, I'm serious...

    import re
    def is_prime (num):
        return re.match(r"^1?$|^(11+?)\1+$",'1'*num) is None