Difference between revisions of "Python notes"
Line 46: | Line 46: | ||
<pre> | <pre> | ||
import hashlib; hashlib.sha1('password').hexdigest() | import hashlib; hashlib.sha1('password').hexdigest() | ||
+ | </pre> | ||
+ | |||
+ | == 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. | ||
+ | |||
+ | <pre> | ||
+ | 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.') | ||
</pre> | </pre> | ||
Revision as of 22:50, 28 October 2008
Contents
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.
hashlib versus sha (python2.5 vs. python2.4)
Python 2.4:
import sha; sha.new('password').hexdigest()
Python 2.5:
import hashlib; hashlib.sha1('password').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