Enumerating formatting strings

Steve Holden steve at holdenweb.com
Mon Apr 18 16:24:39 EDT 2005


I was messing about with formatting and realized that the right kind of 
object could quite easily tell me exactly what accesses are made to the 
mapping in a string % mapping operation. This is a fairly well-known 
technique, modified to tell me what keys would need to be present in any 
mapping used with the format.

class Everything:
     def __init__(self, format="%s", discover=False):
         self.names = {}
         self.values = []
         self.format=format
         self.discover = discover
     def __getitem__(self, key):
         x = self.format % key
         if self.discover:
             self.names[key] = self.names.get(key, 0) + 1
         return x
     def nameList(self):
          if self.names:
              return ["%-20s %d" % i for i in self.names.items()]
          else:
              return self.values
     def __getattr__(self, name):
         print "Attribute", name, "requested"
         return None
     def __repr__(self):
         return "<Everything object at 0x%x>"  % id(self)

def nameCount(template):
     et = Everything(discover=True)
     p = template % et
     nlst = et.nameList()
     nlst.sort()
     return nlst

for s in nameCount("%(name)s %(value)s %(name)s"):
     print s

The result of this effort is:

name                 2
value                1

I've been wondering whether it's possible to perform a similar analysis 
on non-mapping-type format strings, so as to know how long a tuple to 
provide, or whether I'd be forced to lexical analysis of the form string.

regards
  Steve
-- 
Steve Holden        +1 703 861 4237  +1 800 494 3119
Holden Web LLC             http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/




More information about the Python-list mailing list