New Python 3.0 string formatting - really necessary?

M

Michael Torrie

r said:
Thanks MRAB,
except the float is not 2 decimal places, but its there

Come on... They did this for the interpreter not us. It's easer to
parse this string with positional arguments and a dict of format
descriptions. Come on pydev, at least be honest about it!

No. They did this for the *language*. Come on, R. Read the PEP on the
new string formatter. The rationale is very clear.
 
M

MRAB

Michael said:
Some character was needed. It just happens that backslashes have been
used in this manner for composing nonprintable sequences, codes, etc.
It's only in use because someone arbitrarily picked it about 40 years
ago. Any character could have been used; any such character would still
be have to escaped.
BCPL used '*', but C, which was developed from BCPL, uses '\'.
 
R

r

A few years back, there was a certain amount of chest thumping, when
python/django easily beat ror in a benchmark test. Now that ruby is
faster, I guess speed is no big issue.

By the same reasoning, python advocates used to sneer at php because
php constantly broke backward compatibility. Now that python does it,
breaking backward compatibility is no big deal. I guess unicode
support was not that important, until python caught up to perl.

I guess, the way it works is: you first assume that python is
superior, then you figure out why.

I think what walter is saying is the loyalty is gone.

community:
"""If python makes great, if it doesn't, why should "i" care if it
goes down the toilet? i just move to ruby"""

Were is your loyalty pyfans?, Has the fight left you???
 
B

Bruno Desthuilliers

walterbyrd a écrit :
A few years back, there was a certain amount of chest thumping, when
python/django easily beat ror in a benchmark test.

I don't remember it, and honestly, I just don't give a damn.
Now that ruby is
faster,

"faster" than what ? Than Python ? or than it's previous version ?
I guess speed is no big issue.

Please use your google-fu (if you have any). As far as I'm concerned, my
position didn't change these 7+ past years: Python is (and has always
been) fast enough for most of what I use it for (and when it isn't,
neither PHP nor Ruby are going to be solution anyway).

Now improvements are always welcomes, and if you compare 1.5.2 with
2.5.1, you'll find out that the core developpers did improve Python's
perfs.

Now do you have any serious argument, or are you just trolling ?
By the same reasoning, python advocates used to sneer at php because
php constantly broke backward compatibility. Now that python does it,
breaking backward compatibility is no big deal.

There's a lot 1.5.2 days code still running *unmodified* on 2.6.x.
You'll have hard time finding (non-trivial, and even then) PHP3 code
running unmodified on PHP5.
I guess unicode
support was not that important, until python caught up to perl.

I guess, the way it works is: you first assume that python is
superior, then you figure out why.

Whoever said Python was "superior" (except your good friend 'r') ?

As far as I'm concerned, I don't think Python is "superior" (OMG), I
think it's a good language that happens to fit my brain *and* solve more
than 80% of my programmer's needs. If you're not happy with Python's
perfs, please contribute, you are welcome.
 
R

r

As far as I'm concerned, I don't think Python is "superior" (OMG), I
think it's a good language that happens to fit my brain *and* solve more
than 80% of my programmer's needs. If you're not happy with Python's
perfs, please contribute, you are welcome.

He is contributing, by bringing up the subject for debate. Volunteers
exist on all levels, not just the people who write code for CPython.

Every OOS project needs diversity. There is base code, maintenance
code, tutorials, essays, promotion(even if you consider it
fanboyism),etc, etc. """Every spoke on a wheel is just as important as
all the rest""", Bruno.
 
A

Arnaud Delobelle

Steven D'Aprano said:
Instead of just whinging, how about making a suggestion to fix it? Go on,
sit down for an hour or ten and try to work out how a BINARY OPERATOR
like % (that means it can only take TWO arguments) can deal with an
arbitrary number of arguments, *without* having any special cases.

Go on. Take your time. I'll be waiting.

Well that's easy. I see 'r' didn't answer so I will: only accept tuples
on the right hand side of the %, so all arguments have to be put inside
a tuple.
Traceback (most recent call last):
'42'

Of course there would still be the possibility of uncaught bugs when
people forget to put the argument in a tuple if the argument itself is a
tuple of length 1.
.... print "foo(%s)" % x
.... # should be % (x,)
.... foo(1)

That's why .format() is a better option IMHO.
 
A

Aaron Brady

I think what walter is saying is the loyalty is gone.

community:
"""If python makes great, if it doesn't, why should "i" care if it
goes down the toilet?  i just move to ruby"""

Were is your loyalty pyfans?, Has the fight left you???

Point: It is not rational for the crew to go down with the ship, only
the captain.

Case: Loyalty is a complex emotion, and it's not clear that it's our
highest priority, or that it's anyone's.

I want to use a good language. If Python stops being good (that is, a
good version of Python stops being maintained and supported), then
I'll stop using it, and that's the rational thing to do.

Just to be fair, though, it's (contraction) not obviously irrational
for a captain to go down with the ship. The mentality, commitments,
and principles that it lets him keep and make may be better on the
whole in the long run for captains, crews, and ships, only if they
have that consequence. That is, captains that will go down with the
ship are better captains of ships, and captains that have the capacity
to betray, forge, or abandon principles make worse captains; therefore
a good captain will go down, and can't change his mind.

However, as critics and fans of Python, our actions don't really have
the same consequences as the captains. That is, it is not rational
for the crew to go down with the ship, only the captain.
 
R

r

Point: It is not rational for the crew to go down with the ship, only
the captain.

Case: Loyalty is a complex emotion, and it's not clear that it's our
highest priority, or that it's anyone's.

I want to use a good language.  If Python stops being good (that is, a
good version of Python stops being maintained and supported), then
I'll stop using it, and that's the rational thing to do.

Just to be fair, though, it's (contraction) not obviously irrational
for a captain to go down with the ship.  The mentality, commitments,
and principles that it lets him keep and make may be better on the
whole in the long run for captains, crews, and ships, only if they
have that consequence.  That is, captains that will go down with the
ship are better captains of ships, and captains that have the capacity
to betray, forge, or abandon principles make worse captains; therefore
a good captain will go down, and can't change his mind.

However, as critics and fans of Python, our actions don't really have
the same consequences as the captains.  That is, it is not rational
for the crew to go down with the ship, only the captain.

What if the crew sabotage the ship, should the captain still go down
with it, even though sabatuers are to blame?

All ships need a good captain, all captains need a good crew, and all
crews need a good ship.(also True in reverse()). Without loyalty
python will fail, so will Ruby, so will C. Sometimes even when loyalty
is scarce, a language will survive solely because it is the only ship
available.

You do not have to fight for python as I do to use it and benefit from
it, that's OK. I don't care either way. But don't piss on me for
trying to keep her a-float, Mate!.
 
S

Steven D'Aprano

A few years back, there was a certain amount of chest thumping, when
python/django easily beat ror in a benchmark test. Now that ruby is
faster, I guess speed is no big issue.

Who was doing this chest-thumping? Fanboys like "r"? Why should you tar
all of us with their immaturity?

By the same reasoning, python advocates used to sneer at php because php
constantly broke backward compatibility. Now that python does it,
breaking backward compatibility is no big deal.

No, breaking backward compatibility IS a big deal. That's why Python is
doing it slowly and carefully: the minimum amount of breakage necessary,
and with the Python 2.x series kept going in parallel for at least two
additional versions.
I guess unicode support
was not that important, until python caught up to perl.

Python has had unicode support for a long time. You just needed to write
u'' instead of ''.

I guess, the way it works is: you first assume that python is superior,
then you figure out why.

Just keep on trollin'.
 
R

r

Who was doing this chest-thumping? Fanboys like "r"? Why should you tar
all of us with their immaturity?

Walter,
Steven would rather live in a bland Utopian society and could care
less for the greatness of competition and he has little respect for
loyalty. He would like to have little league games where there is no
losers, so nobody's "feelings" get hurt(oh NO!). And EOE so that god
forbid weather or not someone is qualified they must be hired just to
keep a equal balance in the workplace. Hey Steven, we should outlaw
individualism too, God forbid someone think outside the box!(damn
heretics!)

But as they say "ignorance is bliss" ey Stevie?
 
L

Luis M. González

I have not worked with Python enough to really know. But, it seems to
me that more I look at python 3.0, the more I wonder if it isn't a
step backwards.

To me, it seems that this:

print "%s=%d" % ('this',99)

Is much easier, and faster, to type, and is also easier to read and
understand. It also allows people to leverage their knowledge of C.

This (if it's right) is much longer, and requires more special
characters.

print( "{0}={1}".format('this',99))

Maybe it's worth all the extra trouble, and breaking backward
compatibilty, and all. But, I never had the idea that the old way was
all that big a problem. Of course, I could be wrong. Was the old way
all that big of a problem?

Well, I was playing with python 3k a little bit and, as usual, after a
few minutes everything felt natural.
The new string formating is perhaps a little more typing, much is much
more clear and readable.
I know where it came from. Long ago, Guido took a look at Boo, which
is a python-like .NET language, and he posted a comment saying how
much he liked the string formating, which is identical to the new one
in python.

I still can't get used to add the parenthesis to "print", and this is
the only thing I don't like, but I'm sure there's a good reason for
this change...

Luis
 
A

ajaksu

I still can't get used to add the parenthesis to "print", and this is
the only thing I don't like, but I'm sure there's a good reason for
this change...

I should know better than to post such an awful hack:

__past__.py:

from sys import excepthook as sys_excepthook
from sys import modules
---
def printhook(exctype, value, traceback):
skip = True
if isinstance(value, SyntaxError):
if 'print ' in value.text:
printable = value.text.replace('print ', '')[:-1]
skip = False
toprint = 'print(' + printable +')'
print('Trying to convert your mess into', toprint)
try:
exec(toprint)
except NameError as ne:
name = str(ne).replace("name '", '').replace("' is not
defined", '')
try:
var = str(getattr(modules['__main__'], name))
exec('print(' + printable.replace(name, var) +
')')
except AttributeError as ae:
sys_excepthook(NameError, ne, traceback)
except SyntaxError as se:
print('NameError workaround replaced something
bad')
skip = True
except NameError as ne2:
print('Too many names to map to objects :p')
skip = True
except:
print('Sorry, something went wrong and I am too
lazy to find out what')
skip = True
except:
raise
skip = True
if skip:
sys_excepthook(exctype, value, traceback)
---

Then, as I'd check some stuff in parallel on 2.5 and 3.0, I do this on
the 3.0 prompt:
---
import sys
exchook = sys.excepthook
from __past__ import printhook
sys.excepthook = printhook
---

As soon as I wrote that mess^H^H^H^H helper, remembering to use print
() became easier (I think the trauma helped) and I haven't imported
much from __past__ since.

Should I hit 'send'?

Daniel
 
S

Steven D'Aprano

Loss of backward compatibility, mainly.

How do you lose backward compatibility by *adding* new functionality? The
old functionality will continue to work as normal.
 
L

Luis M. González

How do you lose backward compatibility by *adding* new functionality? The
old functionality will continue to work as normal.

AFAIK it still works the old way, but it will be deprecated soon.
 
R

r

You know, it is so much easier to find my posts now that someone has
been thoughtful enough to mark them for me. Thank you kind chaps, i
shall leave a shiny new nickel for you, just send me your name,
address, and phone numbers. I'll get them in the mail right away.
 
A

Arlo Belshee

For R, and others who haven't read the PEP or worked a lot with the
web, here are some really strong advantages of the new string
formatting over the old.

Note: I'm not saying that you have to use one or the other. I'm just
pointing out some of the things that the new format gives us - things
which allow the next generation of application simplification
(especially web apps).

When working on resource-oriented, generalized display applications
(eg, most any modern website), you commonly run into the problem of
wanting to display a bunch of different things in a bunch of different
ways - and on the web, display means "convert to a string for the
browser". However, the mapping is not a complete graph. Rather, there
are usually some rules. For example:

* I want to show the same thing to different people in different
ways, depending on permissions.
* Sometimes I want to show a thing as a full display, and sometimes
as a link to go get more. Usually, the template (context) knows how I
want to show something, but the thing knows how to show itself.

I can solve this using the new string formatting. In particular, by
using the "{0.property}", "{variable[index]}", and similar
substitutions (none of which can be done in the old syntax). As a
result, I end up with an entire website, of an arbitrary number of
pages, being supported with one, 5-line "generate the view" method.
There is 0 code per page.

Here are some of the simpler examples. First, there might be a link to
a user's page:

"<a href='{0.url}">{0.display_name}</a>"

And a link to a blog entry:

"<a href='{0.url}">{0.display_name}</a>"

Wait...isn't that the same? Yup. There's the first widget: a link. Any
resource that knows its own name and URL (and that's all of them) can
be shown as a link. Similar widget extraction hugely reduces the other
combinations I have to support - eliminating a lot of redundancy, and
many LoC.

However, display_name doesn't show up the same for all users.
Administrators often get additional data (such as the username),
everywhere they see a user's name. Friends of a user see little
rollovers that tell them more about that user - such as a photo.
Fortunately, I defined my user class like:

class User:
@property
def display_name(self):
# viewer-dependent context stuff here.

And the new string formatting calls my arbitrary code, without anyone
having to think about it. But display_name doesn't need to know how to
display a name - it just needs to choose which style to use. I can
also extract that out to a template, and then have "<img
src='{0.photo.url}' />{0.first}" for friends and "{0.first} {0.last}
({0.username})" for admins, and so on. My display_name code just needs
to choose which representation to use - it doesn't define that format.
It just returns one of several opaque string constants / widgets,
making refactoring trivial.

Similarly, I can use "{resource.full_display_for_viewer}" or
"{resource.link_display}" to tell the resource how I want it to
display itself.

Hm. Doesn't that make widget sets (a la ToscaWidgets / TuboGears) and
template languages (such as Cheetah / Kid / Mako) a little obsolete?
Well, sorta. After all when displaying my user class, I can do this
too: "{self.blog_entries.recent.as_ordered_list.using.link_display}".
Is that pathological? Probably (unless you have a functional
programming background or like domain-specific languages). Looping is,
after all, one of the things a real templating system gives you.
However, now you don't need to use it for common (and simple) things.

Eventually, you do run into stuff for which you want a full templating
language. And I use them. For example, they define the base page
layouts. The point, however, is that a lot of the lower-level things
can be done without using the templating language. And this reduces
the number of Mako templates you have lying around, while still
allowing great decomposability.

Most of these things could be done by having the object override
__format__(self). However, that jams my display code in with the rest
of my resource class. This way, I can have templates pull out what
they want from my resources. And I can compute the template to use and
the resources to use it on independently, then just pass it to my
displayer method.

These are capabilities that %s has no chance to every approach. The
ability to use new-style format strings reducees my LoC by a half-ton,
and they make what they leave behind a lot easier to read. Being
higher-level constructs, they allow me to eliminate redundancy, and
that's the real purpose of a programmer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,301
Latest member
BuyPureganics

Latest Threads

Top