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

Read more