Python Snippets (4)

1. compile

  1. #!/usr/bin/env python
  2.  
  3. eval_code = compile("100 + 200", "", "eval")
  4. print eval(eval_code)
  5.  
  6. single_code = compile("print 'Hello World'", '', "single")
  7. exec single_code
  8.  
  9. exec_code = compile("""
  10. req = input('Count how many numbers?')
  11. for eachNum in range(req):
  12.     print eachNum
  13.             """, '','exec')
  14. exec exec_code

2.

  1. #! /usr/bin/env python
  2.  
  3. def foo():
  4.     return True
  5. def bar():
  6.     'bar() does not much'
  7.     return True
  8. foo.__doc__ = 'foo() does not do much'
  9. foo.tester = '''
  10. if foo():
  11.     print 'PASSED'
  12. else:
  13.     print 'FAILED'
  14. '''
  15.  
  16. for eachAttr in dir():
  17.     obj = eval(eachAttr) #convert the string to the object
  18.     if isinstance(obj, type(foo)):
  19.         if hasattr(obj, '__doc__'):
  20.             print '\n Function "%s" has a doc string:\n\t%s' %(eachAttr, obj.__doc__)
  21.         if hasattr(obj, 'tester'):
  22.             print 'Function "%s" has a tester...executing ' %eachAttr
  23.             exec obj.tester #to execute the strings
  24.         else:
  25.             print 'Funciton "%s" has no tester...skipping' %eachAttr
  26.     else:
  27.         print '"%s" is not a Function' %eachAttr
  28. print '________________dir()__________________'
  29. print dir()

3.
globals/locals/execfile/

4.

  1. try:
  2.     _count = int(open("counter").read())
  3. except IOError:
  4.     _count = 0
  5.  
  6. def incrcounter(n):
  7.     global _count
  8.     _count = _count + n
  9.  
  10. def savecounter():
  11.     open("counter", "w").write("%d" % _count)
  12.  
  13. import atexit
  14. atexit.register(savecounter)

5.

  1. >>> m = re.findall(r'(the)(dog)' , 'bite thedog thedog')
  2. >>> m
  3. [('the', 'dog'), ('the', 'dog')]
  4. >>>

6.

  1. >>> patt = '^((\w){3}(\d+))(BB)'
  2. >>> m = re.match(patt, 'THU34324BB')
  3. >>> m.groups()
  4. ('THU34324', 'U', '34324', 'BB')
  5. >>>

7.

  1. 一个解决办法是用“非贪婪”操作符,“?”. 这个操作符可以用在 “*”, “+”, 或 “?” 的
  2. 后面。它的作用是要求正则表达式引擎匹配的字符越少越好。因此,如果我们把“?”放在“.+”
  3. 的后面,我们就得到了想要的结果,
  4. >>> patt = '.+?(\d+-\d+-\d+)'
  5. >>> re.match(patt, data).group(1) # subgroup 1 # 子组 1
  6. '1171590364-6-8'

8.
Variable length parameter

  1. #coding:utf-8
  2. def foo(arg1,arg2="OK",*tupleArg,**dictArg):
  3.     print "arg1=",arg1
  4.     print "arg2=",arg2
  5.     for i,element in enumerate(tupleArg):
  6.         print "tupleArg %d-->%s" % (i,str(element))
  7.     for  key in dictArg:
  8.         print "dictArg %s-->%s" %(key,dictArg[key])
  9.  
  10. myList=["my1","my2"]
  11. myDict={"name":"Tom","age":22}
  12. foo("formal_args",arg2="argSecond",a = 2) #a = 2 is assigned to dictArg 
  13. print "*"*40
  14. foo(123,myList,myDict) # because there is no * or **, so this is the common assignment.
  15. print "*"*40
  16. foo(123,rt=123,*myList,**myDict) #this is no rt, so rt belongs to dictArg
  17. -------------------
  18. output:
  19. arg1= formal_args
  20. arg2= argSecond
  21. dictArg a-->2
  22. ****************************************
  23. arg1= 123
  24. arg2= ['my1', 'my2']
  25. tupleArg 0-->{'age': 22, 'name': 'Tom'}
  26. ****************************************
  27. arg1= 123
  28. arg2= my1
  29. tupleArg 0-->my2
  30. dictArg rt-->123
  31. dictArg age-->22
  32. dictArg name-->Tom
  33. [Finished in 0.1s]

9.
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

  1. def f(a, L=[]):
  2.     L.append(a)
  3.     return L
  4.  
  5. print f(1)
  6. print f(2)
  7. print f(3)
  8.  
  9. This will print
  10.  
  11. [1]
  12. [1, 2]
  13. [1, 2, 3]

10.

  1. >>> def make_incrementor(n):
  2. ...     return lambda x: x + n
  3. ...
  4. >>> f = make_incrementor(42)
  5. >>> f(0)
  6. 42
  7. >>> f(1)
  8. 43

发布者

690130229

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

发表评论