Newbie can't figure out documentation practices

Sean Ross sross at connectmail.carleton.ca
Fri May 9 14:09:13 EDT 2003


Here's one way:

class MyClass:
    def __init__(self, z):
        self.z = z
    def test(self, other):
        info = \
"""
var x = %(x)s
var y = %(y)s
var self.z = %(self.z)s
fun x+y+self.z = %(x)s+%(y)s+%(self.z)s
var z from other object = %(other.z)s
z from self plus other = %(self.z)s + %(other.z)s
"""
        x, y = 3, 4
        infodict = locals().copy()
        infodict.update(dict([('self.z', self.z), ('other.z', other.z)]))
        print info % infodict

a = MyClass(1)
b = MyClass(2)
a.test(b)

# outputs
>>>
var x = 3
var y = 4
var self.z = 1
fun x+y+self.z = 3+4+1
var z from other object = 2
z from self plus other = 1 + 2


"Fernando Perez" <fperez528 at yahoo.com> wrote in message
news:b9gn4k$dd9$1 at peabody.colorado.edu...
> sismex01 at hebmex.com wrote:
>
> >> The only other area where you're likely to cry a bit is proper string
> >> interpolation, which sucks in python.
> >>
> >
> > Awww, c'mon, don't scare away the newbies!  Besides, it's
> > really a matter of perception; for me, Python's string
> > interpolation is excellent, specially after working
> > with shell and perl strings. Python's intrpolation feels
> > more first-world-like, more "formal", instead of perl's
> > and sh's.
>
> Ok, time for my yearly rant on interpolation ;)  Can anyone tell me how to
> do cleanly something like (using perl-like syntax to indicate my intent,
> this isn't real code):
>
> print """
> var x = $x
> var y = $y
> var self.z = $self.z
> fun x+y+self.z = $x+$y+$self.z
> var z from other object = $other.z
> z from self plus other = $self.z + $other.z
> """  % ????
>
> I can't use locals() b/c it won't see the members of self and other. I
can't
> update locals() with self/other.__dict__ because they'll clobber each
> other.
>
> In general the only solution I've been able to find is to make a bunch of
> local temporaries to hold all of my object's data plus assorted other
stuff
> in locals() as non-dotted names.  That strikes me as ugly and unpythonic,
> but I've failed to find a better alternative.  I'd love to be enlightened.
>
> I vaguely recall some nice class-based trick I saw a while back, but I'd
> like a more 'standard' mechanism.  Ka-Ping Yee's Itpl class seems
wonderful
> to me, but all attempts to push that have failed so far.
>
> I've been told to write the above with tons of print statements (one per
> line) and even more quotemarks:
>
> print 'x=',x,'self.z=',self.z,...
>
> But I _hate_ that kind of output for anything longer than two or three
> lines.  It's nearly impossible to read smoothly something which is say 50
> lines of the above with many variables.
>
>
> Cheers, and TIA,
>
> f.






More information about the Python-list mailing list