[Python-Dev] features i'd like [Python 3000?] ... #4: interpolated strings ala perl
Josiah Carlson
jcarlson at uci.edu
Mon Dec 4 09:32:46 CET 2006
Ben Wing <ben at 666.com> wrote:
>
> sorry to be casting multiple ideas at once to the list. i've been
> looking into other languages recently and reading the recent PEP's and
> such and it's helped crystallize ideas about what could be better about
> python.
>
> i see in PEP 3101 that there's some work going on to fix up the string
> formatting capabilities of python. it looks good to me but it still
> doesn't really address the lack of a simple interpolated string
> mechanism, as in perl or ruby. i find myself constantly writing stuff like
>
> text="Family: %s" % self.name
[snip]
> maybe_errout(i"[title], line [lineno]: [errstr]\n")
This can be done now via:
maybe_errout("%(title)s, line %(lineno)i: %(errstr)s\n"%locals())
> def __str__(self):
> return i"CCGFeatval([self.name], parents=[self.parents],
> licensing=[self.licensing])"
With the proper mapping, this is trivial...
class namelookup:
def __init__(self, namespace):
self.ns = namespace
def __getitem__(self, name):
ns = self.ns
names = name.split('.')
try:
if names[0] in ns:
ns = ns[names[0]]
names = names[1:]
except IndexError:
raise KeyError("bad namespace")
for n in names:
if hasattr(ns, n):
ns = getattr(ns, n)
else:
return "<name not found>"
return ns
>>> class foo:
... a = 1
... b = 2
...
>>> foo = foo()
>>> print "%(foo.b)i + %(foo.a)i"%namelookup(locals())
2 + 1
>>>
While I understand the desire for better string interpolation, many of
your needs can be covered with pre-existing string formatting. You can
even write a handler for "{2} and {1} or {3}" as "%(2)s and %(1)s or %
(3)s"%positional(a, b, c). Toss it into site.py, and you can use it
whenever.
If you want this to be fully in regards to Py3k, post on the py3k
mailing list: python-3000 at python.org
- Josiah
More information about the Python-Dev
mailing list