Enumerating formatting strings
- From: Steve Holden <steve@xxxxxxxxxxxxx>
- Date: Mon, 18 Apr 2005 16:24:39 -0400
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 nlstfor s in nameCount("%(name)s %(value)s %(name)s"):
print sThe 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/
.
- Follow-Ups:
- Re: Enumerating formatting strings
- From: Greg Ewing
- Re: Enumerating formatting strings
- From: Peter Otten
- Re: Enumerating formatting strings
- From: Bengt Richter
- Re: Enumerating formatting strings
- Prev by Date: Re: Can a function be called within a function ?
- Next by Date: Re: def a((b,c,d),e):
- Previous by thread: Tkinter & Tkconstants
- Next by thread: Re: Enumerating formatting strings
- Index(es):
Relevant Pages
|