[Python-Dev] transitioning from % to {} formatting
Eric Smith
eric at trueblade.com
Fri Oct 2 00:58:31 CEST 2009
Vinay Sajip wrote:
> Good point as far as the general case is concerned, though it's perhaps not that
> critical for logging. By which I mean, it's not unreasonable for
> Formatter.__init__ to grow a "style" keyword parameter which determines whether
> it uses %-, {}- or $-formatting. Then the formatter can look for '%(asctime)s',
> '{asctime}' or '$asctime' according to the style.
It's tangential, but in the str.format case you don't want to check for
just '{asctime}', because you might want '{asctime:%Y-%m-%d}', for example.
But there are ways to delay computing the time until you're sure it's
actually being used in the format string, without parsing the format
string. Now that I think of it, the same technique could be used with
%-formatting:
import datetime
class DelayedStr:
def __init__(self, fn):
self.fn = fn
self.obj = None
def __str__(self):
if self.obj is None:
self.obj = self.fn()
return self.obj.__str__()
def current_time():
print "calculating time"
return datetime.datetime.now()
# will not compute current time
print '%(msg)s' % {'asctime':DelayedStr(current_time),
'msg':'test'}
# will compute current time: same dict used as before
print '%(asctime)s %(msg)s' % {'asctime':DelayedStr(current_time),
'msg':'test'}
Eric.
More information about the Python-Dev
mailing list