Advertisement
ismaelvc

string_interpolation.py

May 14th, 2013
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.86 KB | None | 0 0
  1. #!/usr/bin/env python2
  2.  
  3. '''
  4. string_interpolation 0.5 (Tested on python 2.7.3):
  5.  
  6. Ismael VC           < ismael.vc1337@gmail.com >             May-2013
  7.  
  8. This module provides a simple tool, that eases some of the complexity
  9. of formatting many strings, using a string interpolation aproach.
  10.  
  11. help(interpolate)
  12. '''
  13.  
  14. import sys
  15.  
  16.  
  17. def get_scope(scope):
  18.     scope = scope.lower()
  19.     caller = sys._getframe(2)
  20.     options = ['l', 'local', 'g', 'global']
  21.  
  22.     if scope not in options[:2]:
  23.         if scope in options[2:]:
  24.             return caller.f_globals
  25.         else:
  26.             raise ValueError('invalid mode: {0}'.format(scope))
  27.     return caller.f_locals
  28.  
  29.  
  30. def interpolate(format_string=str(),sequence=None,scope='local',returns=False):
  31.     """
  32.    interpolate([format_string[, sequence | scope[, returns]]]) -> formated string
  33.  
  34.    Prints format_string interpolated with the contents of sequence.
  35.  
  36.    format_string: string to be formated with embeded keyword conversion targets: {}
  37.    sequence: dictionary containing the variables to be substituted in the
  38.                  format_string.
  39.    scope: string specifying which namespace to use, options are, 'l' or 'local'
  40.           and 'g' or 'global'. (Case insensitive)
  41.    returns: if set to True, returns the string instead of printing it.
  42.  
  43.    If sequence is omitted, it defaults to the local namespace.
  44.    """
  45.  
  46.     if type(sequence) is str:
  47.         scope = sequence
  48.         sequence = get_scope(scope)
  49.     else:
  50.         if not sequence:
  51.             sequence = get_scope(scope)
  52.  
  53.     format = 'format_string.format(**sequence)'
  54.     if returns is False:
  55.         print eval(format)
  56.        
  57.     elif returns is True:
  58.         return eval(format)
  59.  
  60.  
  61.  
  62.  
  63.  
  64. ####### Here are some examples and limitations: #######
  65.  
  66. name = 'Maruja'
  67. if __name__ == '__main__':
  68.  
  69.     import time
  70.    
  71.     # I found this elsewhere.
  72.     def print_timing(func):
  73.         def wrapper(*arg):
  74.             t1 = time.time()
  75.             res = func(*arg)
  76.             t2 = time.time()
  77.             diff = (t2-t1)*1000.0
  78.             interpolate('{func.func_name} took: {diff:0.3g}ms\n')
  79.             return res
  80.         return wrapper
  81.  
  82.     @print_timing    
  83.     def interpolation_test():
  84.         print '\nstring_interpolation test:\n'
  85.         print 'First\ttest\tEmpty string:'
  86.         interpolate()
  87.  
  88.         # handle error?
  89.         # interpolate('{}')  
  90.  
  91.         interpolate('Second\ttest:\tNullifying effect. {{}}')  
  92.         interpolate('Third\ttest:\tHello my name is {{name}}.')
  93.         interpolate('Second\ttest:\tWithout conversion target.')
  94.  
  95.         # Cant't use negative indexes, why? Also, interpolate several
  96.         # strings and also from several sequences at the same time?
  97.         names = ['Alejandro', 'Jessica', 'Luis']
  98.         interpolate('''Fourth\ttest:\tHello my name is {names[0]}.
  99. \t\t...no! wait my name is {names[2]},      
  100. \t\tjust kidding my name is {names[0]}!''')
  101.        
  102.         # nonlocal in python 3.x? to interpolate 'Israel'
  103.         name = 'Israel'
  104.         def inner_1():
  105.             interpolate('Fifth\ttest:\tHello my name is {name}.', 'g')
  106.         inner_1()
  107.  
  108.         name = ('Ismael',)
  109.         message_1 = interpolate('Sixth\ttest:\tHello my name is {name[0]}.',
  110.                                     returns=True)
  111.         print message_1        
  112.        
  113.         message_2 = interpolate('Seventh\ttest:\tHello my name is {name}.',
  114.                                 {'name': 'Oscar'}, returns=True)
  115.         print message_2
  116.  
  117.         def inner_2():
  118.             name = 'Monica'
  119.             message_4 = interpolate('Eigth\ttest:\tHello my name is {name}.\n',
  120.                                     returns=True)
  121.             print message_4
  122.         inner_2()    
  123.    
  124.     interpolation_test()
  125.  
  126. ## TEST this code interactively and quickly: http://labs.codecademy.com/BBMF#:workspace  :) ##
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement