473,399 Members | 3,302 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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

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 '06 #1
8 1283
On 6 Dec 2006 09:41:36 -0800, GHUM <ha**************@gmail.comwrote:
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/
Dec 6 '06 #2
"GHUM" <ha**************@gmail.comwrote:
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'])
>>>
Dec 6 '06 #3
"Calvin Spealman" <ir********@gmail.comwrote:
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

Dec 6 '06 #4
On 6 Dec 2006 18:33:26 GMT, Duncan Booth <du**********@invalid.invalidwrote:
"Calvin Spealman" <ir********@gmail.comwrote:
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/
Dec 6 '06 #5
"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 '06 #6
>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

Dec 6 '06 #7
On Wed, 06 Dec 2006 10:58:56 -0800, da****@gmail.com 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.

Dec 7 '06 #8
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!
Dec 7 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: j | last post by:
Anyone here feel that "global variables" is misleading for variables whose scope is file scope? "global" seems to imply global visibility, while this isn't true for variables whose scope is file...
4
by: BB | last post by:
Hello all, I might be missing something here, but am trying to understand the difference between using application-level variables--i.e. Application("MyVar")--and global variables--i.e. public...
8
by: Simone Chiaretta | last post by:
I've a very strange behaveour related to a website we built: from times to times, something should happen on the server, and all static variables inside the web application, both defined inside aspx...
10
by: Bub.Paulson | last post by:
A month ago I finally took the plunge and began learning C# and ASP.Net, coming from a Classic ASP and VBScript background. In my classic ASP, I had my own little library of code that I stuck in...
41
by: none | last post by:
Hello, IIRC, I once saw an explanation how Python doesn't have "variables" in the sense that, say, C does, and instead has bindings from names to objects. Does anyone have a link? Thanks, ...
1
by: Peter | last post by:
Hi sorry, this doesn't really have anything to do with c#, but I wasn't sure where else to post. I am writing some code which needs to parse some text (a string) which is to contain...
12
by: kevineller794 | last post by:
I want to make a split string function, but it's getting complicated. What I want to do is make a function with a String, BeginStr and an EndStr variable, and I want it to return it in a char...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.