Moving from Python 2 to Python 3: A 4 page "cheat sheet"

  • Thread starter Mark Summerfield
  • Start date
M

Mark Dickinson

  Goal: place integer 456 flush-right in a field of width 8

   Py2: "%%%dd" % 8 % 456
   Py3: "{0:{1}d}".format(456, 8)

With str.format(), you don't need to nest one formatting operation within  
another. A little less mind-bending, and every little bit helps!

Or even "{:{}d}".format(456, 8), in 3.1 and 2.7 (when it appears).
But you can do this with % formatting, too. In either 2.x or 3.x:
' 456'
 
C

Carsten Haese

John said:
Goal: place integer 456 flush-right in a field of width 8

Py2: "%%%dd" % 8 % 456
Py3: "{0:{1}d}".format(456, 8)

With str.format(), you don't need to nest one formatting operation
within another.

With string interpolation, you don't need to do that, either.' 456'
 
D

David H Wild

I only just found out that I was supposed to give a different URL:
http://www.informit.com/promotions/promotion.aspx?promo=137519
This leads to a web page where you can download the document (just by
clicking the "Download Now" button), but if you _choose_ you can also
enter your name and email to win some sort of prize.

There is a typographical fault on page 4 of this pdf file. The letter "P"
is missing from the word "Python" at the head of the comparison columns.
 
J

John Bokma

Mark Summerfield said:
If it is any consolation, the second edition should have a much longer
life, now that we have the language moratorium. (I _really_ wanted to
cover 3.1.)

Nah, I wasn't really complaining. Moreover, I am glad I didn't finish
the first edition, so I have less of a problem starting in the 2nd
edition from the beginning. From what I've read in the 1st edition it's
an excellent book.
OK, you got me there,

I knew it ;-) Should've emailed you months ago and maybe it would have
changed in the 2nd edition :-(
I only use Windows for testing purposes and my
personal logon account does have Administrator rights, which I assumed
was standard for personal machines?

I use XP Professional and the first thing I do after installation is
creating a limited user account for my day to day work. As far as I know
this can also be done in XP Home, but I've no experience with home.
Also, the path is short. It is
only a suggestion, it really doesn't matter where you unpack the
examples.

My issue with it is that it somewhat promotes working with Administrator
rights, which is as dangerous as working with root rights on other OSes
if the machine is not connected to the Internet. If it's connected to
the Internet it's way more dangerous, sadly.

Anyway, thanks for writing IMO a very good book, and I *am* happy with a
second edition.
 
M

Mark Summerfield

There is a typographical fault on page 4 of this pdf file. The letter "P"
is missing from the word "Python" at the head of the comparison columns.

I can't see that problem---I've tried the PDF with evince, gv,
acroread, and okular, and no missing "P" on page 4. I don't have a
machine with RISC OS on it so I can't test on that environment!
 
D

David H Wild

I can't see that problem---I've tried the PDF with evince, gv,
acroread, and okular, and no missing "P" on page 4. I don't have a
machine with RISC OS on it so I can't test on that environment!

Using a different pdf reader, on the same machine, the letters are there.
It's an odd thing, because it's only that one page that has the problem.

Thanks, anyway.
 
J

John Posner

With string interpolation, you don't need to do that, either.
' 456'

Thanks, Carsten and Mark D. -- I'd forgotten about the use of "*" in
minimum-field-width specs and precision specs (doh). How about this:

"pi={1:.{0}f} e={2:.{0}f}".format(5, math.pi, math.e)

(result: 'pi=3.14159 e=2.71828')

Can the Python2 %-formating facility handle this without repeating the "5"
argument?

Even if it can, I stand by my original suggestion: include an example to
show that the arguments to str.format() can be used on both the left and
the right of a ":" in a replacement field.

-John
 
T

Terry Reedy

Mark said:
Well it seems clear to me that the BDFL wants to kill of % formatting,
but wasn't able to for Python 3...

Definitely. I thought of adding autonumbering of fields (in 3.1) in
response to his inquiry about the barriers to moving to .format. That
solved 'simplicity of defaults'. The other, 'Autoconversion of installed
base' still awaits.
So I still think it is reasonable
(1) to describe it as deprecated and (2) to only teach and use
str.format().

At the moment (3.1) there are, unfortunately, library packages that
require % for formatting (logging, I believe, for one). There has been
discussion on adding a new option for 3.2, but I do not know what will
happen. Depends on whether you want to be absolutely complete. I
strictly use .format when I can, which so far is always.

Terry Jan Reedy
 
A

Antoine Pitrou

Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a écrit :
I've produced a 4 page document that provides a very concise summary of
Python 2<->3 differences plus the most commonly used new Python 3
features. It is aimed at existing Python 2 programmers who want to start
writing Python 3 programs and want to use Python 3 idioms rather than
those from Python 2 where the idioms differ. [...]

It is available as a free PDF download (no registration or anything)
from InformIT's website. Here's the direct link:

This is great!

Just one thing:

« Copyright © Qtrac Ltd. 2009. All rights reserved »

Might I suggest that you release it under a free license instead?
(such as the CC by, CC by-sa, or the Free Art License)

Regards

Antoine.
 
M

Mark Summerfield

Thanks, Carsten and Mark D. -- I'd forgotten about the use of "*" in  
minimum-field-width specs and precision specs (doh). How about this:

   "pi={1:.{0}f} e={2:.{0}f}".format(5, math.pi, math.e)

   (result: 'pi=3.14159 e=2.71828')

Can the Python2 %-formating facility handle this without repeating the "5"  
argument?

Even if it can, I stand by my original suggestion: include an example to  
show that the arguments to str.format() can be used on both the left and  
the right of a ":" in a replacement field.

-John

I can't squeeze another line into the last column of the last page (I
already tried).

However, a natural place to put this would be in the first section on
the first page. But I want _common_ not _clever_, i.e., an example
that shows a common use of * in % that I can then show using a nested
replacement field. The idea is that people can look at the left hand
column, recognize an idiom they use, and then be able to figure out
from the right hand column how to do the same in Python 3.

Anyway, I've come up with a tiny example and managed to squeeze it in,
so hopefully it'll appear on InformIT's web site in a day or so.
 
M

Mark Summerfield

Which is page 4? The page numbers are missing! (But the column titles
look OK.) :)

I didn't put page numbers or headers or footers on it---seemed
redundant for such a short document.
 
M

Mark Summerfield

Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a écrit :
I've produced a 4 page document that provides a very concise summary of
Python 2<->3 differences plus the most commonly used new Python 3
features. It is aimed at existing Python 2 programmers who want to start
writing Python 3 programs and want to use Python 3 idioms rather than
those from Python 2 where the idioms differ. [...]

It is available as a free PDF download (no registration or anything)
from InformIT's website. Here's the direct link:

This is great!

Just one thing:

« Copyright © Qtrac Ltd. 2009. All rights reserved »

Might I suggest that you release it under a free license instead?
(such as the CC by, CC by-sa, or the Free Art License)

Regards

Antoine.

Good idea---I'll try.
 
W

Wolodja Wentland

On Dec 2, 11:20 am, Wolodja Wentland <[email protected]>
Yes it would be nice, but it isn't quite so simple.
To take sorted() as just one example, it was introduced in 2.4 so
arguably using it isn't valid/idiomatic for Python 2.x programs where
you care about backwards compatibility for the Python 2.x series...

Yes, which is why you could include a 2.X and people who target, say
current +/- 0.1 can choose their poison.
But my main reason for not wanting to do this is that the document is
aimed at people who want to write Python 3, not to encourage people to
stick with 2:)

I actually think that it is the other way round. People should get
familiar with py3 features even if they are not yet ready to
"abandon" py2 (yet). I also think that using some of the backported/supported
features might spur interest in features that are 'py3 only' and therefore
encourage the adoption of py3.

It would also be nice to have a summary of things people can do *now* if
they want to keep the changes from 2to3 to a minimum, which will be with
us for some time. But that is not something *you* have to write .. :)
--
.''`. Wolodja Wentland <[email protected]>
: :' :
`. `'` 4096R/CAF14EFC
`- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)

iQIcBAEBCAAGBQJLF5WsAAoJEIt/fTDK8U78KZUP/19HalgDZuuoG68PykQgH7MN
1+itoTurgid5Jys8o9EgJZxQE2wb3bZpFBrtGHvY17RI5nmSL8GHQ8xojQBg3gVu
syQdPdlf4uxJLK+/y+o3eJMLbuoIxLwrTXy6403voasQ+cZEMljt0WIzBmosUP9Q
RXVKASMQEJo0o5Fy/8ls5TZay6Ut7h9e25337R/PWc+8s6WkzFUszRiHuKeQDliM
gozWP2Jy/uYrsE2/7dWbHyZkT7UsaB9mA5VRDZVEsnwnl1OCo9OYMBgiaqm4zmpw
YXvSihiTMJVGU5hdczwfb+XtgomvtXm6vrWVOBIM0gF/WenbhSD50qXkxFgl+8uz
dimsopDYgdkdcEZ+reDRzfGjxnzsOy3cJoKskyJIrbSz1fBOeKtxyxq5EN1VsBw7
LRzQbfXOLylqmvHp0o44Dx9vB98qz1q3IqjWqep2WFF3qxgC7MRPirHJ1bb4umqy
k0UBwXQxLRPnDfF9jqcK+Q8psLBIm6hwmSPRpCH80BF28IPtaEXKSjSkJU0XHL7i
XDvB/jWqABru2OLRjqL+SvEimTYvHiL30/utJi+aScu8DFmhqOLx3G0SF7Itfaga
AaVbrRCb3KZqzwLKLjFQ/hXLP/l7dTDQep6WMYxRzMGrUXJ6AU8EiGUAg5k2RhPb
l+rbt6qix+XjcKPSMZt4
=OX0f
-----END PGP SIGNATURE-----
 
M

Mark Summerfield

Using a different pdf reader, on the same machine, the letters are there.
It's an odd thing, because it's only that one page that has the problem.

I've never had a problem with my PDFs before. However I use the lout
typesetting system and I suspect that it has some bugs relating to
external links (which normally I don't use but which I've put in this
particular document). Anyway, glad you found something that could read
it:)

BTW issue #2 is now up. This has the file() vs. open() line. Hopefully
issue #3 will follow tomorrow or early next week with a line about
%*d.
 
M

Mark Summerfield

Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a écrit :
I've produced a 4 page document that provides a very concise summary of
Python 2<->3 differences plus the most commonly used new Python 3
features. It is aimed at existing Python 2 programmers who want to start
writing Python 3 programs and want to use Python 3 idioms rather than
those from Python 2 where the idioms differ. [...]

It is available as a free PDF download (no registration or anything)
from InformIT's website. Here's the direct link:

This is great!

Just one thing:

« Copyright © Qtrac Ltd. 2009. All rights reserved »

Might I suggest that you release it under a free license instead?
(such as the CC by, CC by-sa, or the Free Art License)

Regards

OK, issue#3 of the document is now available:
http://www.informit.com/promotions/promotion.aspx?promo=137519

In the light of feedback from [these people] it now has:
- an entry for file() vs. open() [Martin P. Hellwig]
- an entry for %* vs. {:{}} syntax [John Posner, Mark Dickinson, &
Carsten Haese]
- creative commons license "CC by-sa" [Antoine Pitrou]

So I hope it will prove even more useful now:)
 
V

Vinay Sajip

At the moment (3.1) there are, unfortunately, library packages that
require % for formatting (logging, I believe, for one). There has been
discussion on adding a new option for 3.2, but I do not know what will
happen. Depends on whether you want to be absolutely complete. I
strictly use .format when I can, which so far is always.

Logging uses %-style formatting because that was all that was
available at the time it was written. A frequent complaint from some
quarters is about the overhead of logging, and so I'm not sure it's a
good idea to switch over from %-formatting to str.format just for the
sake of it, unless a way can be found which avoids the problems of
lower performance and backwards compatibility (e.g. a foolproof %-
string to {} converter, which I've had a stab at, but which cannot be
achieved without changes to the {} code, e.g. to allow old-style octal
constants). As far as logging is concerned I'll be periodically
looking to see if moving over to the new format without performance/
backwards compatibility compromises is feasible, and when it is I'll
adopt the new format.

For now, AFAIK, people who are determined to use the {}-format can do
so by subclassing logging.Formatter and by passing in message classes
which convert format-string and args to final message. It's a one-time
cost they'd incur (to write the relevant subclasses) which could be
used on multiple projects.

Regards,

Vinay Sajip
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top