Weekly 20140323
30 Python language features and tricks
- Extended unpacking
>>> a, *b, c = [1,2,3,4] >>> b [2,3]
- List slices with negative step
>>> a = [1,3,4,5] >>> a[::-1] [5,4,3,1]
- Name slices (
slice(start, end, slice)
)
>>> LASTTHREE = slice(-3, None, 2) >>> a = [1,2,3,4,5,6] >>> a[LASTTHREE] [4,6]
- Dictionary comprehension
>>> m = {x: x * 3 for x in range(5)} >>> m {0:0, 1:3, 2:6, 3:9, 4:12, 5:15}
- Named tuples
>>> Point = collections.namedtuple('Point', ['x', 'y']) >>> b = Point(11,13) >>> b.y 13
- Use capital letter for set variables
- Counter
>>> from collections import Counter >>> a = Counter([1,1,2,3]) >>> a Counter({1:2, 2:1, 3:1}) >>> a.most_common(1) [(1, 2)]
-
collections.deque
Double-ended queue - default dict
>>> m = collections.defaultdict(int) >>> m['a'] 0 >>> m = collections.defaultdict(str) >>> m['a'] ''
Simple URL encryption
Append a KEY string (with an easy delimitor) to the ID field, then use base64.urlsafe_b64encode
and base64.urlsafe_b64decode
flaskr-tdd
-
TDD:
- write a test
- run the test (it should fail)
- write just enough code to pass the test
- refactor
-
Flask test client
tester = app.test_client(self) response = tester.get('/', content_type="html/text") # response.data include all html text
-
Flask flash system:
get_flashed_messages
--> may be useful for client-side validation -
url_for('static', filename = 'style.css')
Install tagbar on vim
- create .vim/ if not exist
- Install exuberant ctags
- Install tagbar
cd ~/.vim git clone git://github.com/majutsushi/tagbar mv tagbar/* . # must be directly under .vim/ sudo rm -r tagbar/ cd doc/ vim tagbar.txt :helptags . # quit vim
- edit
.vimrc
(below is mine):
let g:tagbar_ctags_bin='/usr/local/bin/ctags' # change to ctags bin path, this is on MacOS let g:tagbar_width=40 noremap <silent> tb :TagbarOpen fj <CR>
- useful key shortcuts:
tb: open tagbar # my key binding p: go to tag, stay in tagbar <enter>: go to tag o: toggle fold *: open all fold =: collapse all fold ?: keymap help
Comments
Comments powered by Disqus