Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Easy "here documents" ??

Reply
Thread Tools

Easy "here documents" ??

 
 
Fredrik Lundh
Guest
Posts: n/a
 
      12-20-2004
Jim Hill wrote:

>>And if you prefer not to type so much:
>>
>>def I(*args): return "".join(map(str, args))
>>def F(v, fmt): return ("%" + fmt) % v

>
> Not that I don't appreciate the suggestions from masters of the Python
> universe, but the reason I'm switching to Python from Perl is for the
> readability. What you fells are suggesting might as well be riddled
> with dollar signs and semicolons... <emoticon>.


the I and F functions? add newlines to them, and replace that ugly-but-
generally-accepted "".join thing with a proper string.join call, split the
second expression into two subexpressions if necessary, and they'll
look a lot better.

or did you mean the call to I? did you look at it in a syntax-coloring
editor?

</F>



 
Reply With Quote
 
 
 
 
Fredrik Lundh
Guest
Posts: n/a
 
      12-20-2004
Jim Hill wrote:

> I'm trying to write a script that writes a script for a rather specialized
> task. I know that seems weird, but the original version was written in
> Korn shell and most of my team are familiar with the way it does things
> even though they don't read Korn.


so why didn't you tell us?

if you want $-style interpolation, you can use the new string.Template
class (mentioned in passing by Nick above); useful examples here:

http://aspn.activestate.com/ASPN/Coo.../Recipe/304004

if you don't have 2.4, you can use the RE machinery for the same purpose;
see e.g.

http://effbot.org/zone/re-sub.htm#simple-templating

</F>



 
Reply With Quote
 
 
 
 
Keith Dart
Guest
Posts: n/a
 
      12-20-2004
Fredrik Lundh wrote:
> Jim Hill wrote:
>
>
>>I'm trying to write a script that writes a script for a rather specialized
>>task. I know that seems weird, but the original version was written in
>>Korn shell and most of my team are familiar with the way it does things
>>even though they don't read Korn.

>
>
> so why didn't you tell us?
>
> if you want $-style interpolation, you can use the new string.Template
> class (mentioned in passing by Nick above); useful examples here:
>
> http://aspn.activestate.com/ASPN/Coo.../Recipe/304004
>
> if you don't have 2.4, you can use the RE machinery for the same purpose;
> see e.g.
>
> http://effbot.org/zone/re-sub.htm#simple-templating


You might also try the following:

---------python--------------
# a self-substituting string object. Just set attribute names to mapping
names
# that are given in the initializer string.
class mapstr(str):
def __new__(cls, initstr, **kwargs):
s = str.__new__(cls, initstr)
return s
def __init__(self, initstr, **kwargs):
d = {}
for name in _findkeys(self):
d[name] = kwargs.get(name, None)
self.__dict__["_attribs"] = d
def __setattr__(self, name, val):
if name not in self.__dict__["_attribs"].keys():
raise AttributeError, "invalid attribute name %r" % (name,)
self.__dict__["_attribs"][name] = val
def __getattr__(self, name):
try:
return self.__dict__["_attribs"][name]
except KeyError:
raise AttributeError, "Invalid attribute %r" % (name,)
def __str__(self):
if None in self._attribs.values():
raise ValueError, "one of the attributes %r is not set" %
(self._attribs.keys(),)
return self % self._attribs
def __call__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
return self % self._attribs
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, str.__repr__(self))
def attributes(self):
return self._attribs.keys()

import re
_findkeys = re.compile(r"%\((\w+)\)").findall
del re

-----------

You use it like this:

TEST = mapstr("some%(one)s one\nsome%(two)s three\nsome%(three)s four")
print TEST.attributes()
TEST.one = "one"
TEST.two = "thing"
TEST.three = "where"
print TEST
s = str(TEST) # makes new, substituted, string
assert s == "someone one\nsomething three\nsomewhere four"

This allows you to use mapping-substitution syntax on a special string
object. But the substituted variables are attributes of the object.
String-ifying it gets the new string with the substitutions made.



--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
Keith Dart <>
public key: ID: F3D288E4
================================================== ===================
 
Reply With Quote
 
Keith Dart
Guest
Posts: n/a
 
      12-20-2004
Fredrik Lundh wrote:
> Jim Hill wrote:
>
>
>>I'm trying to write a script that writes a script for a rather specialized
>>task. I know that seems weird, but the original version was written in
>>Korn shell and most of my team are familiar with the way it does things
>>even though they don't read Korn.

>
>
> so why didn't you tell us?
>
> if you want $-style interpolation, you can use the new string.Template
> class (mentioned in passing by Nick above); useful examples here:
>
> http://aspn.activestate.com/ASPN/Coo.../Recipe/304004
>
> if you don't have 2.4, you can use the RE machinery for the same purpose;
> see e.g.
>
> http://effbot.org/zone/re-sub.htm#simple-templating


You might also try the following:

---------python--------------
# a self-substituting string object. Just set attribute names to mapping
names
# that are given in the initializer string.
class mapstr(str):
def __new__(cls, initstr, **kwargs):
s = str.__new__(cls, initstr)
return s
def __init__(self, initstr, **kwargs):
d = {}
for name in _findkeys(self):
d[name] = kwargs.get(name, None)
self.__dict__["_attribs"] = d
def __setattr__(self, name, val):
if name not in self.__dict__["_attribs"].keys():
raise AttributeError, "invalid attribute name %r" % (name,)
self.__dict__["_attribs"][name] = val
def __getattr__(self, name):
try:
return self.__dict__["_attribs"][name]
except KeyError:
raise AttributeError, "Invalid attribute %r" % (name,)
def __str__(self):
if None in self._attribs.values():
raise ValueError, "one of the attributes %r is not set" %
(self._attribs.keys(),)
return self % self._attribs
def __call__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
return self % self._attribs
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, str.__repr__(self))
def attributes(self):
return self._attribs.keys()

import re
_findkeys = re.compile(r"%\((\w+)\)").findall
del re

-----------

You use it like this:

TEST = mapstr("some%(one)s one\nsome%(two)s three\nsome%(three)s four")
print TEST.attributes()
TEST.one = "one"
TEST.two = "thing"
TEST.three = "where"
print TEST
s = str(TEST) # makes new, substituted, string
assert s == "someone one\nsomething three\nsomewhere four"

This allows you to use mapping-substitution syntax on a special string
object. But the substituted variables are attributes of the object.
String-ifying it gets the new string with the substitutions made.



--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
Keith Dart <>
public key: ID: F3D288E4
================================================== ===================
 
Reply With Quote
 
Scott David Daniels
Guest
Posts: n/a
 
      12-20-2004
Jim Hill wrote:
> Fredrik Lundh wrote:
>
>>Scott David Daniels wrote:
>>
>>
>>>And if you enjoy building insecure stuff, try:
>>>
>>> def fix(text, globals_=None, locals=None, quote='"'):
>>> d = (globals_ or locals or globals()).copy()
>>> source = text.split(quote)
>>> source[1::2] = (str(eval(expr, d, locals or d))

[fixing the !#@!$ tab that snuck in there]
>>> for expr in source[1::2])
>>> return ''.join(source)

>>
>>And if you prefer not to type so much:
>>
>>def I(*args): return "".join(map(str, args))
>>def F(v, fmt): return ("%" + fmt) % v

>
>
> Not that I don't appreciate the suggestions from masters of the Python
> universe, but the reason I'm switching to Python from Perl is for the
> readability. What you fells are suggesting might as well be riddled
> with dollar signs and semicolons... <emoticon>.

Really what I was trying to showing you was that you could use eval and
do arbitrary expressions using sneaky slicing.

v[1::2] is every odd position, and it can be used for replacement.

v[1::2] = [str(eval(txt)) for txt in v[1::2]]

Is likely what you want; it got ugly when I lifted it into a function.
The cute trick is to use a quote delimiter and observe that the odd
positions are the quoted text.

--Scott David Daniels

 
Reply With Quote
 
Nick Craig-Wood
Guest
Posts: n/a
 
      12-20-2004
Jim Hill <> wrote:
> Nick Craig-Wood wrote:
> >I prefer this
> >
> > ... I'll have %(amount)s %(what)s
> > ... for $%(cost)s please""" % locals()

>
> Looks pretty slick. This might just be what I need.
>
> >Its almost as neat as perl / shell here documents and emacs parses """
> >strings properly too

>
> Mmm...emacs...
>
> Thanks for the tip.


You are welcome! I came to python after many years of perl too...

--
Nick Craig-Wood <> -- http://www.craig-wood.com/nick
 
Reply With Quote
 
Doug Holton
Guest
Posts: n/a
 
      12-21-2004
> Jim Hill wrote:
>
>> Is there a way to produce a very long multiline string of output with
>> variables' values inserted without having to resort to this wacky
>>
>> """v = %s"""%(variable)


No, it is currently not possible in Python without the hacks you have
seen already. Python is long overdue for simpler string interpolation
as seen in many other scripting languages.

You should add a feature request to have this in Python 3.0, a.k.a.
Python 3000: http://www.python.org/cgi-bin/moinmoin/Python3.0

Then you could simple do something like:

variable1 = 1
variable2 = 2

s = """
v = ${variable1}
v2's value is: ${variable2}
"""

However, Python 3.0 is likely years away. If you want to know how to
run code like this today, consult Fredrik Lundh.
 
Reply With Quote
 
Bengt Richter
Guest
Posts: n/a
 
      12-21-2004
On Mon, 20 Dec 2004 18:58:09 -0600, Doug Holton <> wrote:

>> Jim Hill wrote:
>>
>>> Is there a way to produce a very long multiline string of output with
>>> variables' values inserted without having to resort to this wacky
>>>
>>> """v = %s"""%(variable)

>
>No, it is currently not possible in Python without the hacks you have
>seen already. Python is long overdue for simpler string interpolation
>as seen in many other scripting languages.
>
>You should add a feature request to have this in Python 3.0, a.k.a.
>Python 3000: http://www.python.org/cgi-bin/moinmoin/Python3.0
>
>Then you could simple do something like:
>
>variable1 = 1
>variable2 = 2
>
>s = """
> v = ${variable1}
> v2's value is: ${variable2}
>"""
>
>However, Python 3.0 is likely years away. If you want to know how to
>run code like this today, consult Fredrik Lundh.


Or replace ${...} with equally simple %(...)s in the above and be happy

>>> variable1 = 1
>>> variable2 = 2
>>>
>>> s = """

... v = ${variable1}
... v2's value is: ${variable2}
... """
>>> print s.replace('${','%(').replace('}',')s') % locals()


v = 1
v2's value is: 2

Better would be to write it with %(...)s in the first place though, or you may need
regex help for correct conversion (if involve other uses for the ${} chars).

Regards,
Bengt Richter
 
Reply With Quote
 
Doug Holton
Guest
Posts: n/a
 
      12-21-2004
Bengt Richter wrote:
>>variable1 = 1
>>variable2 = 2
>>
>>s = """
>> v = ${variable1}
>> v2's value is: ${variable2}
>>"""
>>
>>However, Python 3.0 is likely years away. If you want to know how to
>>run code like this today, consult Fredrik Lundh.

>
>
> Or replace ${...} with equally simple %(...)s in the above and be happy


I'm afraid you are incorrect. Simply replacing the $ with % in my
example will not work in Python.
If you would like to use % instead of $, I recommend requesting that
feature for Python 3.0: http://www.python.org/cgi-bin/moinmoin/Python3.0
 
Reply With Quote
 
Jim Sizelove
Guest
Posts: n/a
 
      12-21-2004
Doug Holton wrote:
> Bengt Richter wrote:
>
>>> variable1 = 1
>>> variable2 = 2
>>>
>>> s = """
>>> v = ${variable1}
>>> v2's value is: ${variable2}
>>> """
>>>
>>> However, Python 3.0 is likely years away. If you want to know how to
>>> run code like this today, consult Fredrik Lundh.

>>
>>
>>
>> Or replace ${...} with equally simple %(...)s in the above and be
>> happy

>
>
> I'm afraid you are incorrect. Simply replacing the $ with % in my
> example will not work in Python.
> If you would like to use % instead of $, I recommend requesting that
> feature for Python 3.0: http://www.python.org/cgi-bin/moinmoin/Python3.0


Oh, but it does work:

>>> variable1 = 1
>>> variable2 = 2
>>> s = """

... v1 = %(variable1)s
... v2's value is: %(variable2)s
... """
>>> print s % vars()


v1 = 1
v2's value is: 2

--Jim
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Easy come, easy go magwhite Wireless Networking 0 12-31-2007 09:29 AM
Is it reasonably easy easy to something like this with python? Bruno Desthuilliers Python 5 08-29-2007 07:40 AM
Stripping audio from qa DVD. Easy or not so easy? GJ Computer Support 1 05-23-2007 02:03 AM
Shared folders - easy question JLunis Wireless Networking 7 03-11-2005 11:33 PM
easy to look at and easy to maintain web page menuing system. Hazzard ASP .Net 2 04-06-2004 03:51 AM



Advertisments