Skip to content
Browse files

Add formatWithCall.

  • Loading branch information...
glyph committed Jun 13, 2013
1 parent c52212e commit 2ba3de085c53aba5064612fde60edf3351b0fb58
Showing with 49 additions and 2 deletions.
  1. +34 −2 twext/python/
  2. +15 −0 twext/python/test/
@@ -18,7 +18,7 @@
Classes and functions to do granular logging.
Example usage in a module:
Example usage in a module::
from twext.python.log import Logger
log = Logger()
@@ -27,7 +27,7 @@
log.debug("Got data: {data}.", data=data)
Or in a class:
Or in a class::
from twext.python.log import Logger
@@ -80,6 +80,8 @@ def oops(self, data):
import logging
import time

from string import Formatter

from zope.interface import Interface, implementer
from twisted.python.constants import NamedConstant, Names
from twisted.python.failure import Failure
@@ -140,6 +142,36 @@ def levelWithName(cls, name):
#LogLevel.critical: logging.CRITICAL,

_theFormatter = Formatter()

class _CallMapping(object):
def __init__(self, submapping):
self._submapping = submapping

def __getitem__(self, key):
callit = key.endswith("()")
realKey = key[:-2] if callit else key
value = self._submapping[realKey]
if callit:
value = value()
return value

def formatWithCall(formatString, mapping):
@param formatString: A PEP-3101 format string.
@type formatString: L{unicode}
@param mapping: A L{dict}-like object to format.
@return: The string with formatted values interpolated.
@rtype: L{unicode}
return _theFormatter.vformat(formatString, (), _CallMapping(mapping))

@@ -23,6 +23,7 @@
from twext.python.log import pythonLogLevelMapping
from twext.python.log import Logger, LegacyLogger

from twext.python.log import formatWithCall
from twistedcaldav.test.util import TestCase

@@ -322,6 +323,20 @@ def test_logInvalidLogLevel(self):
self.assertEquals(len(errors), 1)

def test_formatWithCall(self):
L{formatWithCall} is an extended version of L{unicode.format} that will
interpret a set of parentheses "C{()}" at the end of a format key to
mean that the format key ought to be I{called} rather than stringified.
formatWithCall(u"Hello, {world}. {callme()}.",
callme=lambda: "maybe")),
"Hello, earth. maybe."

def test_formatEvent(self):
Test formatting.

0 comments on commit 2ba3de0

Please sign in to comment.
You can’t perform that action at this time.