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/e[……]

Read more

Python Snippets(3)

1.
*attr()

  1. class myClass(object):
  2.     def __init__(self):
  3.         self.foo = 100
  4. myInst = myClass()
  5. print hasattr(myInst, 'foo')
  6. print getattr(myInst, 'foo')
  7. print hasattr(myInst, 'bar')
  8. #print getattr(myInst, 'bar')
  9. print getattr(myInst, 'bar', 'oooops')
  10. setattr(myInst, 'bar', 'my attr')
  11. print getattr(myInst,'bar')
  12. print dir(myInst)
  13. print getattr(myInst,'bar')
  14. delattr(myInst, 'foo')
  15. print dir(myInst)

2.
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为[……]

Read more

Python snippets (2)

1.
Generators

  1. def simpleGen():
  2.     yield 1
  3.     yield '2--->punch!'
  4.  
  5. myG = simpleGen()
  6. '''
  7. myG.next()
  8. myG.next()
  9. myG.next() #Exception
  10. '''
  11.  
  12. for eachItem in simpleGen():
  13.     print eachItem,
  14.  
  15. print '-----------------------------------------'
  16. from random import randrange
  17. def randGen(aList):
  18.     while len(aList) > 0:
  19.         yield aList.pop(randrange(len(aList)))# Just like list.pop() and random.choice()
  20.  
  21. for item in randGen(['rock', 'paper', 'scissors']):
  22.     print item

2.

  1. import longmodulename
  2. short = longmodulename
  3. del longmodulename
  4.  
  5. from cgi import FieldStorage as form

3.

8238020767628c[……]

Read more