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