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

Discussion in 'Python' started by GHUM, Dec 6, 2006.

  1. GHUM

    GHUM Guest

    imagine:


    template=""" Hello %(name)s, how are you %(action)s"""


    we can use it to do things like:

    print template % dict (name="Guido", action="indenting")


    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?

    Harald
     
    GHUM, Dec 6, 2006
    #1
    1. Advertising

  2. On 6 Dec 2006 09:41:36 -0800, GHUM <> wrote:
    > imagine:
    >
    >
    > template=""" Hello %(name)s, how are you %(action)s"""
    >
    >
    > we can use it to do things like:
    >
    > print template % dict (name="Guido", action="indenting")
    >
    >
    > 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?
    >
    > Harald
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >


    I am not aware of anything in the stdlib to do this easily, but its
    pretty easy to get them. See this example:

    class format_collector(object):
    def __init__(self):
    self.names = []
    def __getitem__(self, name):
    self.names.append(name)
    return ''

    collector = format_collector()
    "%(foo)s %(bar)s" % collector
    assert collector.names == ['foo', 'bar']

    Of course, wrapping this functionality into a simple function is
    straightforward and will look better.

    --
    Read my blog! I depend on your acceptance of my opinion! I am interesting!
    http://ironfroggy-code.blogspot.com/
     
    Calvin Spealman, Dec 6, 2006
    #2
    1. Advertising

  3. GHUM

    Duncan Booth Guest

    "GHUM" <> 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'])
    >>>
     
    Duncan Booth, Dec 6, 2006
    #3
  4. GHUM

    Duncan Booth Guest

    "Calvin Spealman" <> wrote:

    > I am not aware of anything in the stdlib to do this easily, but its
    > pretty easy to get them. See this example:
    >
    > class format_collector(object):
    > def __init__(self):
    > self.names = []
    > def __getitem__(self, name):
    > self.names.append(name)
    > return ''
    >
    > collector = format_collector()
    > "%(foo)s %(bar)s" % collector
    > assert collector.names == ['foo', 'bar']
    >
    > Of course, wrapping this functionality into a simple function is
    > straightforward and will look better.


    You should return a value like 0 instead of ''.

    >>> collector = format_collector()
    >>> "%(foo)s %(bar)d" % collector


    Traceback (most recent call last):
    File "<pyshell#3>", line 1, in <module>
    "%(foo)s %(bar)d" % collector
    TypeError: int argument required
     
    Duncan Booth, Dec 6, 2006
    #4
  5. On 6 Dec 2006 18:33:26 GMT, Duncan Booth <> wrote:
    > "Calvin Spealman" <> wrote:
    >
    > > I am not aware of anything in the stdlib to do this easily, but its
    > > pretty easy to get them. See this example:
    > >
    > > class format_collector(object):
    > > def __init__(self):
    > > self.names = []
    > > def __getitem__(self, name):
    > > self.names.append(name)
    > > return ''
    > >
    > > collector = format_collector()
    > > "%(foo)s %(bar)s" % collector
    > > assert collector.names == ['foo', 'bar']
    > >
    > > Of course, wrapping this functionality into a simple function is
    > > straightforward and will look better.

    >
    > You should return a value like 0 instead of ''.
    >
    > >>> collector = format_collector()
    > >>> "%(foo)s %(bar)d" % collector

    >
    > Traceback (most recent call last):
    > File "<pyshell#3>", line 1, in <module>
    > "%(foo)s %(bar)d" % collector
    > TypeError: int argument required
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >


    Good thinking with returning 0 and using a set. Maybe something added
    to the stdlib would be welcome instead of anyone needing it writing
    this little class?

    --
    Read my blog! I depend on your acceptance of my opinion! I am interesting!
    http://ironfroggy-code.blogspot.com/
     
    Calvin Spealman, Dec 6, 2006
    #5
  6. GHUM

    Guest

    "Is there an easy (i.e.: no regex) way to do get the names of all
    parameters? "

    ....regexp is the easy way :D

    GHUM wrote:
    > imagine:
    >
    >
    > template=""" Hello %(name)s, how are you %(action)s"""
    >
    >
    > we can use it to do things like:
    >
    > print template % dict (name="Guido", action="indenting")
    >
    >
    > 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?
    >
    > Harald
     
    , Dec 6, 2006
    #6
  7. GHUM

    Tim Chase Guest

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

    >
    > 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'])


    (darn, if I didn't have nearly identical code/reply, but two
    posts beat me to the Send button)

    Duncan's solution is a slightly more robust solution (returning 0
    rather than returning the empty string), as format strings allow
    for things like

    "%(food)s costs $%(x)05.2f" % {
    'x':3.14159,
    'food':'a slice of pie'
    }

    which will choke if it gets a string instead of a number for
    attempts to get "x".

    It sure beats trying to hammer out a regexp or some stab at
    pyparsing it. Though I suppose one could do something like

    r = re.compile(r'%\(([^)]*)\)')

    as most of the edge-cases that I can think of that would cause
    problems in a general case would be problems for the string
    formatting as well (balanced parens, etc)

    -tkc
     
    Tim Chase, Dec 6, 2006
    #7
  8. On Wed, 06 Dec 2006 10:58:56 -0800, wrote:

    > "Is there an easy (i.e.: no regex) way to do get the names of all
    > parameters? "
    >
    > ...regexp is the easy way :D


    I'd like to see this regex. And make sure it works correctly with this
    format string:

    """%(key)s
    %%(this is not a key)d
    %%%(but this is)f
    %%%%%%%(%(and so is this)%()%%)u
    and don't forget the empty case %()c
    but not %%%%%%()E
    and remember to handle %(new
    lines)X correctly
    and %(percentages)%."""

    It should list the keys as:

    'key'
    'but this is'
    '%(and so is this)%()%%'
    ''
    'new\nlines'
    'percentages'


    I love easy regexes :)



    --
    Steven.
     
    Steven D'Aprano, Dec 7, 2006
    #8
  9. GHUM

    Tim Chase Guest

    > I'd like to see this regex. And make sure it works correctly with this
    > format string:
    >
    > """%(key)s
    > %%(this is not a key)d
    > %%%(but this is)f
    > %%%%%%%(%(and so is this)%()%%)u
    > and don't forget the empty case %()c
    > but not %%%%%%()E
    > and remember to handle %(new
    > lines)X correctly
    > and %(percentages)%."""
    >
    > It should list the keys as:
    >
    > 'key'
    > 'but this is'
    > '%(and so is this)%()%%'
    > ''
    > 'new\nlines'
    > 'percentages'
    >
    >
    > I love easy regexes :)


    >>> r = re.compile(r'(?<!%)(?:%%)*%\(([^)]*)\)')


    works on all but your pathological '%(and so is this)%()%%' and
    if any programmer working for me used that as their formatting
    variable, they'd either be out of a job, or I would be for hiring
    such a psychopath. :)

    >>> print r.sub(lambda x: '@@@%s@@@' % x.group(0), s)

    @@@%(key)@@@s
    %%(this is not a key)d
    @@@%%%(but this is)@@@f
    @@@%%%%%%%(%(and so is this)@@@@@@%()@@@%%)u
    and don't forget the empty case @@@%()@@@c
    but not %%%%%%()E
    and remember to handle @@@%(new
    lines)@@@X correctly
    and @@@%(percentages)@@@%.
    >>> keys = r.findall(s)
    >>> keys

    ['key', 'but this is', '%(and so is this', '', '', 'new\nlines',
    'percentages']

    The extra empty item (keys[3]) is from that pathological case.
    Otherwise, it seems to do the trick.

    -tkc
    ps: you're a cruel, cruel fellow for throwing out such a
    mind-bender this early in my morning. :) Thanks for the fun!
     
    Tim Chase, Dec 7, 2006
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Smith

    Formating a string

    John Smith, Apr 8, 2006, in forum: ASP .Net
    Replies:
    5
    Views:
    457
    Kevin Spencer
    Apr 9, 2006
  2. Terren

    Formating a String in JAVA

    Terren, Dec 13, 2004, in forum: Java
    Replies:
    6
    Views:
    3,162
    Tilman Bohn
    Dec 13, 2004
  3. Terren

    Formating a String in JAVA

    Terren, Dec 13, 2004, in forum: Java
    Replies:
    6
    Views:
    411
    Tilman Bohn
    Dec 13, 2004
  4. Guest

    String Formating

    Guest, Jun 6, 2005, in forum: Java
    Replies:
    1
    Views:
    385
    Real Gagnon
    Jun 7, 2005
  5. Annie

    Datagrid formating to be inherited by all others

    Annie, Sep 9, 2005, in forum: ASP .Net Datagrid Control
    Replies:
    0
    Views:
    118
    Annie
    Sep 9, 2005
Loading...

Share This Page