Python snippets (1)

1.
Keywords—>with

  1. with open('/etc/passwd','r') as f:
  2.     for eachLine in f:
  3.         print eachLine,

2.
Provide one parameter to assert

  1. >>> assert 1==0, "one does not equal zero silly"
  2. Traceback (most recent call last):
  3.   File "<stdin>", line 1, in <module>
  4. AssertionError: one does not equal zero silly

3.
Imagine how to implement assert with function

  1. def assert(expr, args=None):
  2.     if __debug__ and not expr:
  3.         raise AssertionError, args

4.
Defile new exception class.

  1. class NetworkError(IOError):
  2.     pass
  3.  
  4. class FileError(IOError):
  5.     pass

5.
To check whether one module supports a function or not.

  1. "access" in dir(os)

6.
Function deco

  1. #!/usr/bin/env python
  2.  
  3. from time import ctime, sleep
  4.  
  5. def tsfunc(func):
  6.     def wrappedFunc():
  7.         print '[%s] %s() called' %(ctime(), func.__name__)
  8.         return func()
  9.     return wrappedFunc
  10.  
  11. @tsfunc
  12. def foo():
  13.     pass
  14.  
  15. foo()
  16. sleep(4)
  17.  
  18. for i in range(2):
  19.     sleep(1)
  20.     foo()
  21.  
  22. Output:
  23. ➜  core_python git:(dev) ✗ python deco.py
  24. [Sat Aug 22 20:36:13 2015] foo() called
  25. [Sat Aug 22 20:36:18 2015] foo() called
  26. [Sat Aug 22 20:36:19 2015] foo() called

7
non-fixed args

  1. def tupleVarArgs(arg1, arg2 = 'defaultB', *theRest):
  2.     'Display regular args and non-keyword variable args'
  3.     print 'formal arg 1:', arg1
  4.     print 'formal arg 2:', arg2
  5.  
  6.     for eachArg in theRest:
  7.         print 'another arg:', eachArg
  8.  
  9. if __name__ == '__main__':
  10.     tupleVarArgs('acg')
  11.     tupleVarArgs('23',5.67)
  12.     tupleVarArgs('adf','123',67,90)

7.
filter , map , reduce

  1. #!/usr/bin/env python
  2.  
  3. from random import randint
  4. 'Demonstrate filger'
  5. def testFilter():
  6.     def odd(n):
  7.         return n%2
  8.  
  9.     allNums = []
  10.     for eachNum in range(9):
  11.         allNums.append(randint(1,99))
  12.     print filter(odd, allNums)
  13.  
  14. def testFilterLambda():
  15.     'Using lambda to re-write the code'
  16.     allNums = []
  17.     for eachNum in range(9):
  18.         allNums.append(randint(1,99))
  19.     print filter(lambda n:n%2, allNums)
  20.  
  21. def testFilterList():
  22.     allNums = []
  23.     for eachNum in range(9):
  24.         allNums.append(randint(1, 99))
  25.     print [n for n in allNums if n%2]
  26.  
  27. def testFilterParseList():
  28.     print [n for n in [randint(1, 99) for i in range(9)] if n%2]
  29.  
  30. def testMap():
  31.     print map((lambda x:x+2),[0,1,2,3,4,5,6])
  32.  
  33. def testMapMultiList(): #just he hadoop map/reduce
  34.     print map((lambda x,y:x+y), [1,3,5],[2,4,6])
  35.  
  36. def testMapNoneList(): #Just like zip function
  37.     print map(None, [1,3,5],[2,4,6])
  38.  
  39. def testReduce():
  40.     print 'the total is:',reduce((lambda x,y:x+y),range(5))
  41.  
  42. if __name__ == '__main__':
  43.     print '_'*20
  44.     testFilter()
  45.     testFilterLambda()
  46.     testFilterList()
  47.     testFilterParseList()
  48.     print '_'*20
  49.     testMap()
  50.     testMapMultiList()
  51.     testMapNoneList()
  52.     print '_'*20
  53.     testReduce()
  54.  
  55. '''
  56. Output:
  57. ____________________
  58. [13, 75, 31, 95]
  59. [39, 49, 89, 53, 7]
  60. [25, 77, 95, 79]
  61. [91, 41, 31, 85]
  62. ____________________
  63. [2, 3, 4, 5, 6, 7, 8]
  64. [3, 7, 11]
  65. [(1, 2), (3, 4), (5, 6)]
  66. ____________________
  67. the total is: 10
  68.  
  69. '''

8.
global , local , closure

  1.  
  2. 'Global or Local'
  3.  
  4. def foo():
  5.     m = 3
  6.     def bar():
  7.         n = 4
  8.         print m + n
  9.     print m
  10.     bar()
  11.  
  12. #print m
  13. #bar()
  14. foo()
  15. 'Example about closure'
  16. def counter(start_at = 0):
  17.     count = [start_at]
  18.     def incr():
  19.         count[0] += 1
  20.         return count[0]
  21.     return incr
  22.  
  23. count = conter(5) #From this we can see this seems like the object of a class
  24. print count()
  25. print count()

发布者

690130229

coder,喜欢安静,喜欢读书,wechat: leslie-liya

发表评论