extformat.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #Copyright ReportLab Europe Ltd. 2000-2017
  2. #see license.txt for license details
  3. __version__='3.3.0'
  4. __doc__='''Apparently not used anywhere, purpose unknown!'''
  5. try:
  6. from tokenize import tokenprog
  7. except ImportError:
  8. from tokenize import Token
  9. import re
  10. tokenprog = re.compile(Token)
  11. del Token, re
  12. import sys
  13. def _matchorfail(text, pos):
  14. match = tokenprog.match(text, pos)
  15. if match is None: raise ValueError(text, pos)
  16. return match, match.end()
  17. '''
  18. Extended dictionary formatting
  19. We allow expressions in the parentheses instead of
  20. just a simple variable.
  21. '''
  22. def dictformat(_format, L={}, G={}):
  23. format = _format
  24. S = {}
  25. chunks = []
  26. pos = 0
  27. n = 0
  28. while 1:
  29. pc = format.find("%", pos)
  30. if pc < 0: break
  31. nextchar = format[pc+1]
  32. if nextchar == "(":
  33. chunks.append(format[pos:pc])
  34. pos, level = pc+2, 1
  35. while level:
  36. match, pos = _matchorfail(format, pos)
  37. tstart, tend = match.regs[3]
  38. token = format[tstart:tend]
  39. if token == "(": level = level+1
  40. elif token == ")": level = level-1
  41. vname = '__superformat_%d' % n
  42. n += 1
  43. S[vname] = eval(format[pc+2:pos-1],G,L)
  44. chunks.append('%%(%s)' % vname)
  45. else:
  46. nc = pc+1+(nextchar=="%")
  47. chunks.append(format[pos:nc])
  48. pos = nc
  49. if pos < len(format): chunks.append(format[pos:])
  50. return (''.join(chunks)) % S
  51. def magicformat(format):
  52. """Evaluate and substitute the appropriate parts of the string."""
  53. frame = sys._getframe(1)
  54. return dictformat(format,frame.f_locals, frame.f_globals)
  55. if __name__=='__main__':
  56. from reportlab.lib.formatters import DecimalFormatter
  57. _DF={}
  58. def df(n,dp=2,ds='.',ts=','):
  59. try:
  60. _df = _DF[dp,ds]
  61. except KeyError:
  62. _df = _DF[dp,ds] = DecimalFormatter(places=dp,decimalSep=ds,thousandSep=ts)
  63. return _df(n)
  64. from reportlab.lib.extformat import magicformat
  65. Z={'abc': ('ab','c')}
  66. x = 300000.23
  67. percent=79.2
  68. class dingo:
  69. a=3
  70. print((magicformat('''
  71. $%%(df(x,dp=3))s --> $%(df(x,dp=3))s
  72. $%%(df(x,dp=2,ds=',',ts='.'))s --> $%(df(x,dp=2,ds=',',ts='.'))s
  73. %%(percent).2f%%%% --> %(percent).2f%%
  74. %%(dingo.a)s --> %(dingo.a)s
  75. %%(Z['abc'][0])s --> %(Z['abc'][0])s
  76. ''')))
  77. def func0(aa=1):
  78. def func1(bb=2):
  79. print((magicformat('bb=%(bb)s Z=%(Z)r')))
  80. func1('BB')
  81. func0('AA')