how to get all the "variables" of a string formating?

Duncan Booth duncan.booth at invalid.invalid
Wed Dec 6 12:56:05 EST 2006


"GHUM" <haraldarminmassa at gmail.com> wrote:

> Is there an easy (i.e.: no regex) way to do get the names of all
> parameters?
> 
> get_parameters(template) should return ["name", "action"]
> 
> 
> Python has to do this somewhere internally..... how to access this
> knowledge?

How about:

class gpHelper:
    def __init__(self):
        self.names = set()
    def __getitem__(self, name):
        self.names.add(name)
        return 0
	
def get_parameters(template):
    hlp = gpHelper()
    template % hlp
    return hlp.names

>>> template=""" Hello %(name)s, how are you %(action)s"""
>>> get_parameters(template)
set(['action', 'name'])
>>> 



More information about the Python-list mailing list