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