[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Fab-user] String interpolations
From: |
Niklas Lindström |
Subject: |
[Fab-user] String interpolations |
Date: |
Wed, 13 May 2009 15:12:35 +0200 |
Hi!
I've finally had a bit of time to check out Fabric 0.9. It looks
great! The module reorganisation looks clean and well-thought out (and
I really like the stuff in fabric.contrib).
However, I do miss the string interpolation feature of the older
versions. I can understand if it wasn't ideal (too
implicit/unpythonic, using "non-standard" syntax etc). And I don't
mind having to do *some* explicit invokation to expand variables. But
I never was much of a fan of using string building and/or modula
formatting alá classic python *in these scenarios*. Thus I wonder if
it would be nice to reintroduce some form of utility for it?
Of course, I can just do e.g.:
run("cd %(some_dir)s && cmd %(a_dir)s" % env)
But I *really* dislike the arcane syntax, especially the trailing "s".
And at least my fabric scripts uses interpolation quite often, which
makes it very noisy IMHO.
I tried out one version based on the str.format-stuff in Python
2.6/3.0 ([1], [2]). My take was basically:
import sys
def fmt(s):
caller_locals = sys._getframe(1).f_locals
return s.format(**caller_locals)
class Env:
def __init__(self):
self.a, self.b = "hello", "world"
env = Env()
c = "etc"
print fmt("Say {env.a} {env.b}, {c}.")
This also solves a desire of mine of having a convenient way to use
both env and local vars easily in the same fashion.
Unfortunately I haven't found any pure-python implementation of the
new `str.format` method. (The one at [3] lacks dot-access.) And
dragging some other external templating into this feels too
desperate..
Another option might be e.g. adding a `fmt` method on env (placing it
in env to avoid the _getframe "hack"), and use `string.Template` in
that (available since Python 2.4). It could be used like:
run(env.fmt("cd $some_dir && cmd $a_dir"))
, optionally taking a dict arg and/or kwargs to supply more names to
interpolate.. I'd probably always do a `fmt = env.fmt` at the top of
my scripts, and use the builtin `vars()` as extra arg where needed;
but that's me. ;)
Any thoughts or alternate suggestions? I'd gladly put something
together if we reach consensus.
Best regards,
Niklas
[1] = <http://www.python.org/dev/peps/pep-3101/>
[2] = <http://docs.python.org/library/string.html#new-string-formatting>
[3] = <http://svn.python.org/view/sandbox/trunk/pep3101/>
- [Fab-user] String interpolations,
Niklas Lindström <=
Re: [Fab-user] String interpolations, s s, 2009/05/13