From 70a6b49821a3226f55e9716f32d802d06640cb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Walter=20D=C3=B6rwald?= Date: Thu, 12 Feb 2004 17:35:32 +0000 Subject: Replace backticks with repr() or "%r" From SF patch #852334. --- Demo/classes/Complex.py | 8 +-- Demo/classes/Dates.py | 15 +++--- Demo/classes/Dbm.py | 10 ++-- Demo/classes/Range.py | 4 +- Demo/classes/bitvec.py | 34 ++++++------ Demo/metaclasses/Enum.py | 6 +-- Demo/metaclasses/Meta.py | 2 +- Demo/metaclasses/Trace.py | 2 +- Demo/newmetaclasses/Enum.py | 4 +- Demo/pdist/RCSProxy.py | 2 +- Demo/pdist/client.py | 2 +- Demo/pdist/cmdfw.py | 6 +-- Demo/pdist/cmptree.py | 10 ++-- Demo/pdist/cvslock.py | 2 +- Demo/pdist/rcslib.py | 4 +- Demo/pdist/server.py | 4 +- Demo/rpc/T.py | 2 +- Demo/rpc/rnusersclient.py | 2 +- Demo/rpc/rpc.py | 30 +++++------ Demo/rpc/xdr.py | 3 +- Demo/scripts/eqfix.py | 19 ++++--- Demo/scripts/from.py | 2 +- Demo/scripts/ftpstats.py | 2 +- Demo/scripts/lpwatch.py | 16 +++--- Demo/scripts/markov.py | 4 +- Demo/scripts/mboxconvert.py | 4 +- Demo/scripts/mkrcs.py | 20 +++---- Demo/scripts/mpzpi.py | 2 +- Demo/scripts/newslist.py | 2 +- Demo/scripts/pp.py | 2 +- Demo/sockets/broadcast.py | 2 +- Demo/sockets/ftp.py | 2 +- Demo/sockets/gopher.py | 24 ++++----- Demo/sockets/mcast.py | 4 +- Demo/sockets/radio.py | 2 +- Demo/sockets/telnet.py | 2 +- Demo/sockets/udpecho.py | 4 +- Demo/sockets/unicast.py | 2 +- Demo/sockets/unixclient.py | 2 +- Demo/threads/Coroutine.py | 7 ++- Demo/threads/find.py | 6 +-- Demo/threads/sync.py | 4 +- Demo/threads/telnet.py | 8 +-- Demo/tix/samples/DirList.py | 2 +- Demo/tkinter/guido/mbox.py | 2 +- Demo/tkinter/guido/solitaire.py | 2 +- Demo/tkinter/matt/animation-w-velocity-ctrl.py | 2 +- Demo/tkinter/matt/pong-demo-1.py | 2 +- Doc/lib/caseless.py | 8 +-- Doc/tools/cvsinfo.py | 2 +- Doc/tools/refcounts.py | 2 +- Doc/tools/sgmlconv/esistools.py | 6 +-- Doc/tools/sgmlconv/latex2esis.py | 18 +++---- Lib/BaseHTTPServer.py | 10 ++-- Lib/Bastion.py | 2 +- Lib/CGIHTTPServer.py | 14 ++--- Lib/ConfigParser.py | 10 ++-- Lib/HTMLParser.py | 8 +-- Lib/StringIO.py | 4 +- Lib/aifc.py | 4 +- Lib/atexit.py | 4 +- Lib/base64.py | 2 +- Lib/bdb.py | 4 +- Lib/binhex.py | 4 +- Lib/bsddb/dbrecio.py | 4 +- Lib/bsddb/dbtables.py | 10 ++-- Lib/bsddb/test/test_associate.py | 4 +- Lib/bsddb/test/test_basics.py | 8 +-- Lib/bsddb/test/test_dbtables.py | 2 +- Lib/calendar.py | 8 +-- Lib/cgi.py | 19 ++++--- Lib/difflib.py | 8 +-- Lib/dis.py | 16 +++--- Lib/distutils/cmd.py | 4 +- Lib/distutils/core.py | 2 +- Lib/distutils/dir_util.py | 2 +- Lib/distutils/dist.py | 4 +- Lib/distutils/fancy_getopt.py | 2 +- Lib/distutils/util.py | 16 +++--- Lib/doctest.py | 24 ++++----- Lib/formatter.py | 18 +++---- Lib/fpformat.py | 6 +-- Lib/ftplib.py | 8 +-- Lib/gopherlib.py | 6 +-- Lib/gzip.py | 2 +- Lib/idlelib/ColorDelegator.py | 2 +- Lib/idlelib/EditorWindow.py | 10 ++-- Lib/idlelib/FileList.py | 6 +-- Lib/idlelib/GrepDialog.py | 2 +- Lib/idlelib/ObjectBrowser.py | 2 +- Lib/idlelib/ParenMatch.py | 2 +- Lib/idlelib/PyShell.py | 18 +++---- Lib/idlelib/RemoteDebugger.py | 4 +- Lib/idlelib/ScriptBinding.py | 6 +-- Lib/idlelib/TreeWidget.py | 2 +- Lib/idlelib/UndoDelegator.py | 4 +- Lib/idlelib/WidgetRedirector.py | 2 +- Lib/idlelib/aboutDialog.py | 5 +- Lib/idlelib/configDialog.py | 4 +- Lib/idlelib/configHandler.py | 27 +++++----- Lib/idlelib/rpc.py | 10 ++-- Lib/idlelib/textView.py | 2 +- Lib/ihooks.py | 8 +-- Lib/imaplib.py | 6 +-- Lib/lib-tk/FileDialog.py | 2 +- Lib/lib-tk/Tix.py | 4 +- Lib/lib-tk/Tkinter.py | 12 ++--- Lib/lib-tk/turtle.py | 10 ++-- Lib/macurl2path.py | 4 +- Lib/markupbase.py | 11 ++-- Lib/mhlib.py | 21 ++++---- Lib/mimetools.py | 4 +- Lib/modulefinder.py | 8 +-- Lib/nntplib.py | 10 ++-- Lib/opcode.py | 2 +- Lib/pdb.py | 16 +++--- Lib/pickle.py | 22 ++++---- Lib/pipes.py | 10 ++-- Lib/plat-irix5/cddb.py | 8 ++- Lib/plat-irix5/cdplayer.py | 3 +- Lib/plat-irix5/flp.py | 4 +- Lib/plat-irix5/panel.py | 2 +- Lib/plat-irix5/readcd.py | 4 +- Lib/plat-irix5/torgb.py | 5 +- Lib/plat-irix6/cddb.py | 8 ++- Lib/plat-irix6/cdplayer.py | 3 +- Lib/plat-irix6/flp.py | 4 +- Lib/plat-irix6/panel.py | 2 +- Lib/plat-irix6/readcd.py | 4 +- Lib/plat-irix6/torgb.py | 5 +- Lib/plat-mac/EasyDialogs.py | 4 +- Lib/plat-mac/FrameWork.py | 6 +-- Lib/plat-mac/MiniAEFrame.py | 3 +- Lib/plat-mac/aetypes.py | 55 ++++++++++---------- Lib/plat-mac/argvemulator.py | 3 +- Lib/plat-mac/buildtools.py | 2 +- Lib/plat-mac/gensuitemodule.py | 58 ++++++++++----------- Lib/plat-mac/ic.py | 4 +- Lib/plat-riscos/rourl2path.py | 4 +- Lib/popen2.py | 6 +-- Lib/poplib.py | 16 +++--- Lib/posixfile.py | 2 +- Lib/pprint.py | 6 +-- Lib/pre.py | 10 ++-- Lib/profile.py | 4 +- Lib/pstats.py | 13 ++--- Lib/regsub.py | 6 +-- Lib/repr.py | 12 +++-- Lib/rexec.py | 2 +- Lib/sgmllib.py | 6 +-- Lib/shlex.py | 8 +-- Lib/site.py | 2 +- Lib/smtplib.py | 8 +-- Lib/stringold.py | 2 +- Lib/sunaudio.py | 2 +- Lib/tabnanny.py | 17 +++--- Lib/telnetlib.py | 4 +- Lib/test/test_asynchat.py | 2 +- Lib/test/test_builtin.py | 4 +- Lib/test/test_contains.py | 12 ++--- Lib/test/test_copy.py | 4 +- Lib/test/test_descr.py | 28 +++++----- Lib/test/test_fcntl.py | 4 +- Lib/test/test_generators.py | 2 +- Lib/test/test_grammar.py | 4 +- Lib/test/test_hash.py | 2 +- Lib/test/test_math.py | 8 +-- Lib/test/test_minidom.py | 2 +- Lib/test/test_mpz.py | 2 +- Lib/test/test_poll.py | 2 +- Lib/test/test_popen2.py | 6 +-- Lib/test/test_pprint.py | 26 +++++----- Lib/test/test_pty.py | 2 +- Lib/test/test_pyexpat.py | 6 +-- Lib/test/test_repr.py | 8 +-- Lib/test/test_rotor.py | 4 +- Lib/test/test_select.py | 2 +- Lib/test/test_set.py | 4 +- Lib/test/test_sets.py | 4 +- Lib/test/test_socketserver.py | 2 +- Lib/test/test_struct.py | 18 +++---- Lib/test/test_syntax.py | 2 +- Lib/test/test_types.py | 4 +- Lib/test/test_univnewlines.py | 6 +-- Lib/test/test_weakref.py | 2 +- Lib/toaiff.py | 5 +- Lib/trace.py | 2 +- Lib/unittest.py | 8 +-- Lib/urllib.py | 10 ++-- Lib/warnings.py | 22 ++++---- Lib/wave.py | 2 +- Lib/xdrlib.py | 2 +- Lib/xml/dom/domreg.py | 2 +- Lib/xml/dom/minidom.py | 4 +- Lib/xml/dom/xmlbuilder.py | 2 +- Lib/xmllib.py | 12 ++--- Mac/Demo/PICTbrowse/ICONbrowse.py | 6 +-- Mac/Demo/PICTbrowse/PICTbrowse.py | 8 +-- Mac/Demo/PICTbrowse/PICTbrowse2.py | 6 +-- Mac/Demo/PICTbrowse/cicnbrowse.py | 6 +-- Mac/Demo/PICTbrowse/oldPICTbrowse.py | 8 +-- Mac/Demo/calldll/testcalldll.py | 4 +- Mac/Demo/imgbrowse/imgbrowse.py | 2 +- Mac/Demo/mlte/mlted.py | 2 +- Mac/Demo/resources/listres.py | 4 +- Mac/Demo/textedit/ped.py | 2 +- Mac/Demo/waste/htmled.py | 8 +-- Mac/Demo/waste/swed.py | 4 +- Mac/Demo/waste/wed.py | 2 +- Mac/IDE scripts/Widget demos/KeyTester.py | 2 +- Mac/IDE scripts/Widget demos/WidgetTest.py | 2 +- Mac/Tools/IDE/FontSettings.py | 10 ++-- Mac/Tools/IDE/PyDebugger.py | 2 +- Mac/Tools/IDE/PyDocSearch.py | 2 +- Mac/Tools/IDE/PyEdit.py | 12 ++--- Mac/Tools/IDE/PyFontify.py | 2 +- Mac/Tools/IDE/PythonIDEMain.py | 6 +-- Mac/Tools/IDE/Wapplication.py | 4 +- Mac/Tools/IDE/Wbase.py | 10 ++-- Mac/Tools/IDE/Wsocket.py | 10 ++-- Mac/Tools/IDE/Wtraceback.py | 4 +- Mac/Tools/macfreeze/macfreezegui.py | 2 +- Mac/Tools/macfreeze/macgen_info.py | 2 +- Mac/Tools/macfreeze/macgenerate.py | 2 +- Modules/cgen.py | 40 +++++++------- Tools/bgen/bgen/scantools.py | 64 +++++++++++------------ Tools/compiler/compile.py | 3 +- Tools/faqwiz/faqwiz.py | 8 +-- Tools/freeze/makefreeze.py | 2 +- Tools/freeze/winmakemakefile.py | 2 +- Tools/modulator/modulator.py | 30 +++++------ Tools/scripts/byteyears.py | 2 +- Tools/scripts/checkappend.py | 12 ++--- Tools/scripts/checkpyc.py | 18 +++---- Tools/scripts/classfix.py | 19 ++++--- Tools/scripts/dutree.py | 2 +- Tools/scripts/fixcid.py | 18 +++---- Tools/scripts/fixps.py | 2 +- Tools/scripts/ftpmirror.py | 72 ++++++++++++-------------- Tools/scripts/methfix.py | 19 ++++--- Tools/scripts/pathfix.py | 16 +++--- Tools/scripts/redemo.py | 2 +- Tools/scripts/suff.py | 2 +- Tools/scripts/texi2html.py | 20 +++---- Tools/scripts/untabify.py | 2 +- Tools/scripts/which.py | 2 +- 246 files changed, 926 insertions(+), 962 deletions(-) diff --git a/Demo/classes/Complex.py b/Demo/classes/Complex.py index 4585f62..a9f5c2e 100755 --- a/Demo/classes/Complex.py +++ b/Demo/classes/Complex.py @@ -117,15 +117,15 @@ class Complex: def __repr__(self): if not self.im: - return 'Complex(%s)' % `self.re` + return 'Complex(%r)' % (self.re,) else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) + return 'Complex(%r, %r)' % (self.re, self.im) def __str__(self): if not self.im: - return `self.re` + return repr(self.re) else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) + return 'Complex(%r, %r)' % (self.re, self.im) def __neg__(self): return Complex(-self.re, -self.im) diff --git a/Demo/classes/Dates.py b/Demo/classes/Dates.py index 06ffa36..f8f0634 100755 --- a/Demo/classes/Dates.py +++ b/Demo/classes/Dates.py @@ -86,7 +86,7 @@ _DI400Y = _days_before_year( 400 ) # number of days in 400 years def _num2date( n ): # return date with ordinal n if type(n) not in _INT_TYPES: - raise TypeError, 'argument must be integer: ' + `type(n)` + raise TypeError, 'argument must be integer: %r' % type(n) ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj del ans.ord, ans.month, ans.day, ans.year # un-initialize it @@ -120,10 +120,10 @@ def _num2day( n ): # return weekday name of day with ordinal n class Date: def __init__( self, month, day, year ): if not 1 <= month <= 12: - raise ValueError, 'month must be in 1..12: ' + `month` + raise ValueError, 'month must be in 1..12: %r' % (month,) dim = _days_in_month( month, year ) if not 1 <= day <= dim: - raise ValueError, 'day must be in 1..' + `dim` + ': ' + `day` + raise ValueError, 'day must be in 1..%r: %r' % (dim, day) self.month, self.day, self.year = month, day, year self.ord = _date2num( self ) @@ -142,15 +142,16 @@ class Date: # print as, e.g., Mon 16 Aug 1993 def __repr__( self ): - return '%.3s %2d %.3s ' % ( + return '%.3s %2d %.3s %r' % ( self.weekday(), self.day, - _MONTH_NAMES[self.month-1] ) + `self.year` + _MONTH_NAMES[self.month-1], + self.year) # Python 1.1 coerces neither int+date nor date+int def __add__( self, n ): if type(n) not in _INT_TYPES: - raise TypeError, 'can\'t add ' + `type(n)` + ' to date' + raise TypeError, 'can\'t add %r to date' % type(n) return _num2date( self.ord + n ) __radd__ = __add__ # handle int+date @@ -177,7 +178,7 @@ DateTestError = 'DateTestError' def test( firstyear, lastyear ): a = Date(9,30,1913) b = Date(9,30,1914) - if `a` != 'Tue 30 Sep 1913': + if repr(a) != 'Tue 30 Sep 1913': raise DateTestError, '__repr__ failure' if (not a < b) or a == b or a > b or b != b: raise DateTestError, '__cmp__ failure' diff --git a/Demo/classes/Dbm.py b/Demo/classes/Dbm.py index 5566f99..482806a 100755 --- a/Demo/classes/Dbm.py +++ b/Demo/classes/Dbm.py @@ -13,7 +13,7 @@ class Dbm: def __repr__(self): s = '' for key in self.keys(): - t = `key` + ': ' + `self[key]` + t = repr(key) + ': ' + repr(self[key]) if s: t = ', ' + t s = s + t return '{' + s + '}' @@ -22,13 +22,13 @@ class Dbm: return len(self.db) def __getitem__(self, key): - return eval(self.db[`key`]) + return eval(self.db[repr(key)]) def __setitem__(self, key, value): - self.db[`key`] = `value` + self.db[repr(key)] = repr(value) def __delitem__(self, key): - del self.db[`key`] + del self.db[repr(key)] def keys(self): res = [] @@ -37,7 +37,7 @@ class Dbm: return res def has_key(self, key): - return self.db.has_key(`key`) + return self.db.has_key(repr(key)) def test(): diff --git a/Demo/classes/Range.py b/Demo/classes/Range.py index ebd1817..68f3c61 100755 --- a/Demo/classes/Range.py +++ b/Demo/classes/Range.py @@ -34,9 +34,9 @@ class Range: self.step = step self.len = max(0, int((self.stop - self.start) / self.step)) - # implement `x` and is also used by print x + # implement repr(x) and is also used by print x def __repr__(self): - return 'range' + `self.start, self.stop, self.step` + return 'range(%r, %r, %r)' % (self.start, self.stop, self.step) # implement len(x) def __len__(self): diff --git a/Demo/classes/bitvec.py b/Demo/classes/bitvec.py index ed89d67..2894a56 100755 --- a/Demo/classes/bitvec.py +++ b/Demo/classes/bitvec.py @@ -20,7 +20,7 @@ def _compute_len(param): mant, l = math.frexp(float(param)) bitmask = 1L << l if bitmask <= param: - raise 'FATAL', '(param, l) = ' + `param, l` + raise 'FATAL', '(param, l) = %r' % ((param, l),) while l: bitmask = bitmask >> 1 if param & bitmask: @@ -167,10 +167,10 @@ class BitVec: def __repr__(self): ##rprt('.' + '__repr__()\n') - return 'bitvec' + `self._data, self._len` + return 'bitvec(%r, %r)' % (self._data, self._len) def __cmp__(self, other, *rest): - #rprt(`self`+'.__cmp__'+`(other, ) + rest`+'\n') + #rprt('%r.__cmp__%r\n' % (self, (other,) + rest)) if type(other) != type(self): other = apply(bitvec, (other, ) + rest) #expensive solution... recursive binary, with slicing @@ -193,16 +193,16 @@ class BitVec: def __len__(self): - #rprt(`self`+'.__len__()\n') + #rprt('%r.__len__()\n' % (self,)) return self._len def __getitem__(self, key): - #rprt(`self`+'.__getitem__('+`key`+')\n') + #rprt('%r.__getitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) return self._data & (1L << key) != 0 def __setitem__(self, key, value): - #rprt(`self`+'.__setitem__'+`key, value`+'\n') + #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value)) key = _check_key(self._len, key) #_check_value(value) if value: @@ -211,14 +211,14 @@ class BitVec: self._data = self._data & ~(1L << key) def __delitem__(self, key): - #rprt(`self`+'.__delitem__('+`key`+')\n') + #rprt('%r.__delitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) #el cheapo solution... self._data = self[:key]._data | self[key+1:]._data >> key self._len = self._len - 1 def __getslice__(self, i, j): - #rprt(`self`+'.__getslice__'+`i, j`+'\n') + #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i >= j: return BitVec(0L, 0) @@ -234,7 +234,7 @@ class BitVec: return BitVec(ndata, nlength) def __setslice__(self, i, j, sequence, *rest): - #rprt(`self`+'.__setslice__'+`(i, j, sequence) + rest`+'\n') + #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest)) i, j = _check_slice(self._len, i, j) if type(sequence) != type(self): sequence = apply(bitvec, (sequence, ) + rest) @@ -247,7 +247,7 @@ class BitVec: self._len = self._len - j + i + sequence._len def __delslice__(self, i, j): - #rprt(`self`+'.__delslice__'+`i, j`+'\n') + #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i == 0 and j == self._len: self._data, self._len = 0L, 0 @@ -256,13 +256,13 @@ class BitVec: self._len = self._len - j + i def __add__(self, other): - #rprt(`self`+'.__add__('+`other`+')\n') + #rprt('%r.__add__(%r)\n' % (self, other)) retval = self.copy() retval[self._len:self._len] = other return retval def __mul__(self, multiplier): - #rprt(`self`+'.__mul__('+`multiplier`+')\n') + #rprt('%r.__mul__(%r)\n' % (self, multiplier)) if type(multiplier) != type(0): raise TypeError, 'sequence subscript not int' if multiplier <= 0: @@ -281,7 +281,7 @@ class BitVec: return retval def __and__(self, otherseq, *rest): - #rprt(`self`+'.__and__'+`(otherseq, ) + rest`+'\n') + #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type @@ -290,7 +290,7 @@ class BitVec: def __xor__(self, otherseq, *rest): - #rprt(`self`+'.__xor__'+`(otherseq, ) + rest`+'\n') + #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type @@ -299,7 +299,7 @@ class BitVec: def __or__(self, otherseq, *rest): - #rprt(`self`+'.__or__'+`(otherseq, ) + rest`+'\n') + #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type @@ -308,13 +308,13 @@ class BitVec: def __invert__(self): - #rprt(`self`+'.__invert__()\n') + #rprt('%r.__invert__()\n' % (self,)) return BitVec(~self._data & ((1L << self._len) - 1), \ self._len) def __coerce__(self, otherseq, *rest): #needed for *some* of the arithmetic operations - #rprt(`self`+'.__coerce__'+`(otherseq, ) + rest`+'\n') + #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) return self, otherseq diff --git a/Demo/metaclasses/Enum.py b/Demo/metaclasses/Enum.py index 13a3ed7..df1d814 100644 --- a/Demo/metaclasses/Enum.py +++ b/Demo/metaclasses/Enum.py @@ -107,9 +107,9 @@ class EnumInstance: return self.__value def __repr__(self): - return "EnumInstance(%s, %s, %s)" % (`self.__classname`, - `self.__enumname`, - `self.__value`) + return "EnumInstance(%r, %r, %r)" % (self.__classname, + self.__enumname, + self.__value) def __str__(self): return "%s.%s" % (self.__classname, self.__enumname) diff --git a/Demo/metaclasses/Meta.py b/Demo/metaclasses/Meta.py index 39cbef6..5534074 100644 --- a/Demo/metaclasses/Meta.py +++ b/Demo/metaclasses/Meta.py @@ -98,7 +98,7 @@ def _test(): def __init__(self, *args): print "__init__, args =", args def m1(self, x): - print "m1(x=%s)" %`x` + print "m1(x=%r)" % (x,) print C x = C() print x diff --git a/Demo/metaclasses/Trace.py b/Demo/metaclasses/Trace.py index 86e199d..ea12cd9 100644 --- a/Demo/metaclasses/Trace.py +++ b/Demo/metaclasses/Trace.py @@ -117,7 +117,7 @@ def _test(): def m2(self, y): return self.x + y __trace_output__ = sys.stdout class D(C): - def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y) + def m2(self, y): print "D.m2(%r)" % (y,); return C.m2(self, y) __trace_output__ = None x = C(4321) print x diff --git a/Demo/newmetaclasses/Enum.py b/Demo/newmetaclasses/Enum.py index 8a00b59..5d490a9 100644 --- a/Demo/newmetaclasses/Enum.py +++ b/Demo/newmetaclasses/Enum.py @@ -97,7 +97,7 @@ def _test(): print Color.red - print `Color.red` + print repr(Color.red) print Color.red == Color.red print Color.red == Color.blue print Color.red == 1 @@ -139,7 +139,7 @@ def _test2(): print Color.red - print `Color.red` + print repr(Color.red) print Color.red == Color.red print Color.red == Color.blue print Color.red == 1 diff --git a/Demo/pdist/RCSProxy.py b/Demo/pdist/RCSProxy.py index 7212ca6..87c65cc 100755 --- a/Demo/pdist/RCSProxy.py +++ b/Demo/pdist/RCSProxy.py @@ -188,7 +188,7 @@ def test(): if callable(attr): print apply(attr, tuple(sys.argv[2:])) else: - print `attr` + print repr(attr) else: print "%s: no such attribute" % what sys.exit(2) diff --git a/Demo/pdist/client.py b/Demo/pdist/client.py index 3e93f1c..a00f005 100755 --- a/Demo/pdist/client.py +++ b/Demo/pdist/client.py @@ -139,7 +139,7 @@ class SecureClient(Client, Security): line = self._rf.readline() challenge = string.atoi(string.strip(line)) response = self._encode_challenge(challenge) - line = `long(response)` + line = repr(long(response)) if line[-1] in 'Ll': line = line[:-1] self._wf.write(line + '\n') self._wf.flush() diff --git a/Demo/pdist/cmdfw.py b/Demo/pdist/cmdfw.py index a0c6f5d..25584b7 100755 --- a/Demo/pdist/cmdfw.py +++ b/Demo/pdist/cmdfw.py @@ -55,7 +55,7 @@ class CommandFrameWork: try: method = getattr(self, mname) except AttributeError: - return self.usage("command %s unknown" % `cmd`) + return self.usage("command %r unknown" % (cmd,)) try: flags = getattr(self, fname) except AttributeError: @@ -75,7 +75,7 @@ class CommandFrameWork: print "-"*40 print "Options:" for o, a in opts: - print 'option', o, 'value', `a` + print 'option', o, 'value', repr(a) print "-"*40 def ready(self): @@ -137,7 +137,7 @@ def test(): for t in tests: print '-'*10, t, '-'*10 sts = x.run(t) - print "Exit status:", `sts` + print "Exit status:", repr(sts) if __name__ == '__main__': diff --git a/Demo/pdist/cmptree.py b/Demo/pdist/cmptree.py index 7eaa6c3..8a34f3f 100755 --- a/Demo/pdist/cmptree.py +++ b/Demo/pdist/cmptree.py @@ -49,7 +49,7 @@ def askint(prompt, default): def compare(local, remote, mode): print - print "PWD =", `os.getcwd()` + print "PWD =", repr(os.getcwd()) sums_id = remote._send('sumlist') subdirs_id = remote._send('listsubdirs') remote._flush() @@ -64,13 +64,13 @@ def compare(local, remote, mode): for name, rsum in sums: rsumdict[name] = rsum if not lsumdict.has_key(name): - print `name`, "only remote" + print repr(name), "only remote" if 'r' in mode and 'c' in mode: recvfile(local, remote, name) else: lsum = lsumdict[name] if lsum != rsum: - print `name`, + print repr(name), rmtime = remote.mtime(name) lmtime = local.mtime(name) if rmtime > lmtime: @@ -86,7 +86,7 @@ def compare(local, remote, mode): print for name in lsumdict.keys(): if not rsumdict.keys(): - print `name`, "only locally", + print repr(name), "only locally", fl() if 'w' in mode and 'c' in mode: sendfile(local, remote, name) @@ -160,7 +160,7 @@ def recvfile(local, remote, name): return rv finally: if not ok: - print "*** recvfile of %s failed, deleting" % `name` + print "*** recvfile of %r failed, deleting" % (name,) local.delete(name) def recvfile_real(local, remote, name): diff --git a/Demo/pdist/cvslock.py b/Demo/pdist/cvslock.py index a421e1a..75f866e 100755 --- a/Demo/pdist/cvslock.py +++ b/Demo/pdist/cvslock.py @@ -114,7 +114,7 @@ class Lock: self.delay = delay self.lockdir = None self.lockfile = None - pid = `os.getpid()` + pid = repr(os.getpid()) self.cvslck = self.join(CVSLCK) self.cvsrfl = self.join(CVSRFL + pid) self.cvswfl = self.join(CVSWFL + pid) diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py index 4e72766..78de111 100755 --- a/Demo/pdist/rcslib.py +++ b/Demo/pdist/rcslib.py @@ -232,7 +232,7 @@ class RCS: """ name, rev = self._unmangle(name_rev) if not self.isvalid(name): - raise os.error, 'not an rcs file %s' % `name` + raise os.error, 'not an rcs file %r' % (name,) return name, rev # --- Internal methods --- @@ -252,7 +252,7 @@ class RCS: namev = self.rcsname(name) if rev: cmd = cmd + ' ' + rflag + rev - return os.popen("%s %s" % (cmd, `namev`)) + return os.popen("%s %r" % (cmd, namev)) def _unmangle(self, name_rev): """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. diff --git a/Demo/pdist/server.py b/Demo/pdist/server.py index 423d583..4e4ab0d 100755 --- a/Demo/pdist/server.py +++ b/Demo/pdist/server.py @@ -134,11 +134,11 @@ class SecureServer(Server, Security): response = string.atol(string.strip(response)) except string.atol_error: if self._verbose > 0: - print "Invalid response syntax", `response` + print "Invalid response syntax", repr(response) return 0 if not self._compare_challenge_response(challenge, response): if self._verbose > 0: - print "Invalid response value", `response` + print "Invalid response value", repr(response) return 0 if self._verbose > 1: print "Response matches challenge. Go ahead!" diff --git a/Demo/rpc/T.py b/Demo/rpc/T.py index abf3a06..2adf486 100644 --- a/Demo/rpc/T.py +++ b/Demo/rpc/T.py @@ -18,5 +18,5 @@ def TSTOP(*label): [u, s, r] = tt msg = '' for x in label: msg = msg + (x + ' ') - msg = msg + `u` + ' user, ' + `s` + ' sys, ' + `r` + ' real\n' + msg = msg + '%r user, %r sys, %r real\n' % (u, s, r) sys.stderr.write(msg) diff --git a/Demo/rpc/rnusersclient.py b/Demo/rpc/rnusersclient.py index e9cad62..90cbd6d 100644 --- a/Demo/rpc/rnusersclient.py +++ b/Demo/rpc/rnusersclient.py @@ -77,7 +77,7 @@ def test(): line = strip0(line) name = strip0(name) host = strip0(host) - print `name`, `host`, `line`, time, idle + print "%r %r %r %s %s" % (name, host, line, time, idle) def testbcast(): c = BroadcastRnusersClient('') diff --git a/Demo/rpc/rpc.py b/Demo/rpc/rpc.py index f44b3e4..6b15db4 100644 --- a/Demo/rpc/rpc.py +++ b/Demo/rpc/rpc.py @@ -93,10 +93,10 @@ class Unpacker(xdr.Unpacker): xid = self.unpack_uint(xid) temp = self.unpack_enum() if temp <> CALL: - raise BadRPCFormat, 'no CALL but ' + `temp` + raise BadRPCFormat, 'no CALL but %r' % (temp,) temp = self.unpack_uint() if temp <> RPCVERSION: - raise BadRPCVerspion, 'bad RPC version ' + `temp` + raise BadRPCVerspion, 'bad RPC version %r' % (temp,) prog = self.unpack_uint() vers = self.unpack_uint() proc = self.unpack_uint() @@ -109,7 +109,7 @@ class Unpacker(xdr.Unpacker): xid = self.unpack_uint() mtype = self.unpack_enum() if mtype <> REPLY: - raise RuntimeError, 'no REPLY but ' + `mtype` + raise RuntimeError, 'no REPLY but %r' % (mtype,) stat = self.unpack_enum() if stat == MSG_DENIED: stat = self.unpack_enum() @@ -117,15 +117,15 @@ class Unpacker(xdr.Unpacker): low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ - 'MSG_DENIED: RPC_MISMATCH: ' + `low, high` + 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),) if stat == AUTH_ERROR: stat = self.unpack_uint() raise RuntimeError, \ - 'MSG_DENIED: AUTH_ERROR: ' + `stat` - raise RuntimeError, 'MSG_DENIED: ' + `stat` + 'MSG_DENIED: AUTH_ERROR: %r' % (stat,) + raise RuntimeError, 'MSG_DENIED: %r' % (stat,) if stat <> MSG_ACCEPTED: raise RuntimeError, \ - 'Neither MSG_DENIED nor MSG_ACCEPTED: ' + `stat` + 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,) verf = self.unpack_auth() stat = self.unpack_enum() if stat == PROG_UNAVAIL: @@ -134,13 +134,13 @@ class Unpacker(xdr.Unpacker): low = self.unpack_uint() high = self.unpack_uint() raise RuntimeError, \ - 'call failed: PROG_MISMATCH: ' + `low, high` + 'call failed: PROG_MISMATCH: %r' % ((low, high),) if stat == PROC_UNAVAIL: raise RuntimeError, 'call failed: PROC_UNAVAIL' if stat == GARBAGE_ARGS: raise RuntimeError, 'call failed: GARBAGE_ARGS' if stat <> SUCCESS: - raise RuntimeError, 'call failed: ' + `stat` + raise RuntimeError, 'call failed: %r' % (stat,) return xid, verf # Caller must get procedure-specific part of reply @@ -350,8 +350,8 @@ class RawTCPClient(Client): xid, verf = u.unpack_replyheader() if xid <> self.lastxid: # Can't really happen since this is TCP... - raise RuntimeError, 'wrong xid in reply ' + `xid` + \ - ' instead of ' + `self.lastxid` + raise RuntimeError, 'wrong xid in reply %r instead of %r' % ( + xid, self.lastxid) # Client using UDP to a specific port @@ -701,7 +701,7 @@ class Server: self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() - methname = 'handle_' + `proc` + methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: @@ -840,7 +840,7 @@ def testbcast(): bcastaddr = '' def rh(reply, fromaddr): host, port = fromaddr - print host + '\t' + `reply` + print host + '\t' + repr(reply) pmap = BroadcastUDPPortMapperClient(bcastaddr) pmap.set_reply_handler(rh) pmap.set_timeout(5) @@ -858,7 +858,7 @@ def testsvr(): def handle_1(self): arg = self.unpacker.unpack_string() self.turn_around() - print 'RPC function 1 called, arg', `arg` + print 'RPC function 1 called, arg', repr(arg) self.packer.pack_string(arg + arg) # s = S('', 0x20000000, 1, 0) @@ -888,4 +888,4 @@ def testclt(): c = C(host, 0x20000000, 1) print 'making call...' reply = c.call_1('hello, world, ') - print 'call returned', `reply` + print 'call returned', repr(reply) diff --git a/Demo/rpc/xdr.py b/Demo/rpc/xdr.py index 41c970a..5338aef 100644 --- a/Demo/rpc/xdr.py +++ b/Demo/rpc/xdr.py @@ -184,8 +184,7 @@ class Unpacker: x = self.unpack_uint() if x == 0: break if x <> 1: - raise RuntimeError, \ - '0 or 1 expected, got ' + `x` + raise RuntimeError, '0 or 1 expected, got %r' % (x, ) item = unpack_item() list.append(item) return list diff --git a/Demo/scripts/eqfix.py b/Demo/scripts/eqfix.py index 583d54e..2139d2b 100755 --- a/Demo/scripts/eqfix.py +++ b/Demo/scripts/eqfix.py @@ -58,12 +58,12 @@ def ispython(name): return ispythonprog.match(name) >= 0 def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') + dbg('recursedown(%r)\n' % (dirname,)) bad = 0 try: names = os.listdir(dirname) except os.error, msg: - err(dirname + ': cannot list directory: ' + `msg` + '\n') + err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() subdirs = [] @@ -80,11 +80,11 @@ def recursedown(dirname): return bad def fix(filename): -## dbg('fix(' + `filename` + ')\n') +## dbg('fix(%r)\n' % (dirname,)) try: f = open(filename, 'r') except IOError, msg: - err(filename + ': cannot open: ' + `msg` + '\n') + err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) tempname = os.path.join(head, '@' + tail) @@ -122,14 +122,13 @@ def fix(filename): g = open(tempname, 'w') except IOError, msg: f.close() - err(tempname+': cannot create: '+\ - `msg`+'\n') + err('%s: cannot create: %r\n' % (tempname, msg)) return 1 f.seek(0) lineno = 0 rep(filename + ':\n') continue # restart from the beginning - rep(`lineno` + '\n') + rep(repr(lineno) + '\n') rep('< ' + line) rep('> ' + newline) if g is not None: @@ -146,17 +145,17 @@ def fix(filename): statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) except os.error, msg: - err(tempname + ': warning: chmod failed (' + `msg` + ')\n') + err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') except os.error, msg: - err(filename + ': warning: backup failed (' + `msg` + ')\n') + err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) except os.error, msg: - err(filename + ': rename failed (' + `msg` + ')\n') + err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes return 0 diff --git a/Demo/scripts/from.py b/Demo/scripts/from.py index d61afde..3c04fcd 100755 --- a/Demo/scripts/from.py +++ b/Demo/scripts/from.py @@ -31,5 +31,5 @@ while 1: if not line or line == '\n': break if line.startswith('Subject: '): - print `line[9:-1]`, + print repr(line[9:-1]), print diff --git a/Demo/scripts/ftpstats.py b/Demo/scripts/ftpstats.py index 28b1d8b..79cbee6 100755 --- a/Demo/scripts/ftpstats.py +++ b/Demo/scripts/ftpstats.py @@ -60,7 +60,7 @@ def main(): if search and string.find(line, search) < 0: continue if prog.match(line) < 0: - print 'Bad line', lineno, ':', `line` + print 'Bad line', lineno, ':', repr(line) continue items = prog.group(1, 2, 3, 4, 5, 6) (logtime, loguser, loghost, logfile, logbytes, diff --git a/Demo/scripts/lpwatch.py b/Demo/scripts/lpwatch.py index 9f051eb..00afba9 100755 --- a/Demo/scripts/lpwatch.py +++ b/Demo/scripts/lpwatch.py @@ -83,24 +83,24 @@ def makestatus(name, thisuser): lines.append(line) # if totaljobs: - line = `(totalbytes+1023)/1024` + ' K' + line = '%d K' % ((totalbytes+1023)/1024) if totaljobs <> len(users): - line = line + ' (' + `totaljobs` + ' jobs)' + line = line + ' (%d jobs)' % totaljobs if len(users) == 1: - line = line + ' for ' + users.keys()[0] + line = line + ' for %s' % (users.keys()[0],) else: - line = line + ' for ' + `len(users)` + ' users' + line = line + ' for %d users' % len(users) if userseen: if aheadjobs == 0: - line = line + ' (' + thisuser + ' first)' + line = line + ' (%s first)' % thisuser else: - line = line + ' (' + `(aheadbytes+1023)/1024` - line = line + ' K before ' + thisuser + ')' + line = line + ' (%d K before %s)' % ( + (aheadbytes+1023)/1024, thisuser) lines.append(line) # sts = pipe.close() if sts: - lines.append('lpq exit status ' + `sts`) + lines.append('lpq exit status %r' % (sts,)) return string.joinfields(lines, ': ') try: diff --git a/Demo/scripts/markov.py b/Demo/scripts/markov.py index e1649f1..b0583d1 100755 --- a/Demo/scripts/markov.py +++ b/Demo/scripts/markov.py @@ -89,8 +89,8 @@ def test(): if debug > 1: for key in m.trans.keys(): if key is None or len(key) < histsize: - print `key`, m.trans[key] - if histsize == 0: print `''`, m.trans[''] + print repr(key), m.trans[key] + if histsize == 0: print repr(''), m.trans[''] print while 1: data = m.get() diff --git a/Demo/scripts/mboxconvert.py b/Demo/scripts/mboxconvert.py index 08e0d0c..996537d 100755 --- a/Demo/scripts/mboxconvert.py +++ b/Demo/scripts/mboxconvert.py @@ -73,7 +73,7 @@ def mmdf(f): sts = message(f, line) or sts else: sys.stderr.write( - 'Bad line in MMFD mailbox: %s\n' % `line`) + 'Bad line in MMFD mailbox: %r\n' % (line,)) return sts counter = 0 # for generating unique Message-ID headers @@ -89,7 +89,7 @@ def message(f, delimiter = ''): t = time.mktime(tt) else: sys.stderr.write( - 'Unparseable date: %s\n' % `m.getheader('Date')`) + 'Unparseable date: %r\n' % (m.getheader('Date'),)) t = os.fstat(f.fileno())[stat.ST_MTIME] print 'From', email, time.ctime(t) # Copy RFC822 header diff --git a/Demo/scripts/mkrcs.py b/Demo/scripts/mkrcs.py index 36a35ea..917b4fe 100755 --- a/Demo/scripts/mkrcs.py +++ b/Demo/scripts/mkrcs.py @@ -12,13 +12,13 @@ def main(): rcstree = 'RCStree' rcs = 'RCS' if os.path.islink(rcs): - print `rcs`, 'is a symlink to', `os.readlink(rcs)` + print '%r is a symlink to %r' % (rcs, os.readlink(rcs)) return if os.path.isdir(rcs): - print `rcs`, 'is an ordinary directory' + print '%r is an ordinary directory' % (rcs,) return if os.path.exists(rcs): - print `rcs`, 'is a file?!?!' + print '%r is a file?!?!' % (rcs,) return # p = os.getcwd() @@ -29,26 +29,26 @@ def main(): # (2) up is the same directory as p # Ergo: # (3) join(up, down) is the current directory - #print 'p =', `p` + #print 'p =', repr(p) while not os.path.isdir(os.path.join(p, rcstree)): head, tail = os.path.split(p) - #print 'head =', `head`, '; tail =', `tail` + #print 'head = %r; tail = %r' % (head, tail) if not tail: - print 'Sorry, no ancestor dir contains', `rcstree` + print 'Sorry, no ancestor dir contains %r' % (rcstree,) return p = head up = os.path.join(os.pardir, up) down = os.path.join(tail, down) - #print 'p =', `p`, '; up =', `up`, '; down =', `down` + #print 'p = %r; up = %r; down = %r' % (p, up, down) there = os.path.join(up, rcstree) there = os.path.join(there, down) there = os.path.join(there, rcs) if os.path.isdir(there): - print `there`, 'already exists' + print '%r already exists' % (there, ) else: - print 'making', `there` + print 'making %r' % (there,) makedirs(there) - print 'making symlink', `rcs`, '->', `there` + print 'making symlink %r -> %r' % (rcs, there) os.symlink(there, rcs) def makedirs(p): diff --git a/Demo/scripts/mpzpi.py b/Demo/scripts/mpzpi.py index 93c74aa..ccf591d 100755 --- a/Demo/scripts/mpzpi.py +++ b/Demo/scripts/mpzpi.py @@ -27,7 +27,7 @@ def main(): def output(d): # Use write() to avoid spaces between the digits # Use int(d) to avoid a trailing L after each digit - sys.stdout.write(`int(d)`) + sys.stdout.write(repr(int(d))) # Flush so the output is seen immediately sys.stdout.flush() diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py index f78ca30..b06b452 100755 --- a/Demo/scripts/newslist.py +++ b/Demo/scripts/newslist.py @@ -304,7 +304,7 @@ def getallgroups(server): def getnewgroups(server, treedate): print 'Getting list of new groups since start of '+treedate+'...', info = server.newgroups(treedate,'000001')[1] - print 'got '+`len(info)`+'.' + print 'got %d.' % len(info) print 'Processing...', groups = [] for i in info: diff --git a/Demo/scripts/pp.py b/Demo/scripts/pp.py index 64e57ee..92a1104 100755 --- a/Demo/scripts/pp.py +++ b/Demo/scripts/pp.py @@ -125,6 +125,6 @@ fp.write(program) fp.flush() if DFLAG: import pdb - pdb.run('execfile(' + `tfn` + ')') + pdb.run('execfile(%r)' % (tfn,)) else: execfile(tfn) diff --git a/Demo/sockets/broadcast.py b/Demo/sockets/broadcast.py index a02b081..010162c 100755 --- a/Demo/sockets/broadcast.py +++ b/Demo/sockets/broadcast.py @@ -10,7 +10,7 @@ s.bind(('', 0)) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) while 1: - data = `time.time()` + '\n' + data = repr(time.time()) + '\n' s.sendto(data, ('', MYPORT)) time.sleep(2) diff --git a/Demo/sockets/ftp.py b/Demo/sockets/ftp.py index 8260c52..9e1d5a1 100755 --- a/Demo/sockets/ftp.py +++ b/Demo/sockets/ftp.py @@ -91,7 +91,7 @@ def sendportcmd(s, f, port): hostname = gethostname() hostaddr = gethostbyname(hostname) hbytes = string.splitfields(hostaddr, '.') - pbytes = [`port/256`, `port%256`] + pbytes = [repr(port/256), repr(port%256)] bytes = hbytes + pbytes cmd = 'PORT ' + string.joinfields(bytes, ',') s.send(cmd + '\r\n') diff --git a/Demo/sockets/gopher.py b/Demo/sockets/gopher.py index a2ab3a2..4e1cb30 100755 --- a/Demo/sockets/gopher.py +++ b/Demo/sockets/gopher.py @@ -75,10 +75,10 @@ def get_menu(selector, host, port): typechar = line[0] parts = string.splitfields(line[1:], TAB) if len(parts) < 4: - print '(Bad line from server:', `line`, ')' + print '(Bad line from server: %r)' % (line,) continue if len(parts) > 4: - print '(Extra info from server:', parts[4:], ')' + print '(Extra info from server: %r)' % (parts[4:],) parts.insert(0, typechar) list.append(parts) f.close() @@ -154,17 +154,17 @@ def browse_menu(selector, host, port): list = get_menu(selector, host, port) while 1: print '----- MENU -----' - print 'Selector:', `selector` + print 'Selector:', repr(selector) print 'Host:', host, ' Port:', port print for i in range(len(list)): item = list[i] typechar, description = item[0], item[1] - print string.rjust(`i+1`, 3) + ':', description, + print string.rjust(repr(i+1), 3) + ':', description, if typename.has_key(typechar): print typename[typechar] else: - print '' + print '' print while 1: try: @@ -221,7 +221,7 @@ def browse_textfile(selector, host, port): def browse_search(selector, host, port): while 1: print '----- SEARCH -----' - print 'Selector:', `selector` + print 'Selector:', repr(selector) print 'Host:', host, ' Port:', port print try: @@ -240,9 +240,9 @@ def browse_search(selector, host, port): # "Browse" telnet-based information, i.e. open a telnet session def browse_telnet(selector, host, port): if selector: - print 'Log in as', `selector` + print 'Log in as', repr(selector) if type(port) <> type(''): - port = `port` + port = repr(port) sts = os.system('set -x; exec telnet ' + host + ' ' + port) if sts: print 'Exit status:', sts @@ -307,18 +307,18 @@ def open_savefile(): try: p = os.popen(cmd, 'w') except IOError, msg: - print `cmd`, ':', msg + print repr(cmd), ':', msg return None - print 'Piping through', `cmd`, '...' + print 'Piping through', repr(cmd), '...' return p if savefile[0] == '~': savefile = os.path.expanduser(savefile) try: f = open(savefile, 'w') except IOError, msg: - print `savefile`, ':', msg + print repr(savefile), ':', msg return None - print 'Saving to', `savefile`, '...' + print 'Saving to', repr(savefile), '...' return f # Test program diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py index cc7a7e0..71bcc75 100755 --- a/Demo/sockets/mcast.py +++ b/Demo/sockets/mcast.py @@ -38,7 +38,7 @@ def sender(flag): ttl = struct.pack('b', 1) # Time-to-live s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl) while 1: - data = `time.time()` + data = repr(time.time()) ## data = data + (1400 - len(data)) * '\0' s.sendto(data, (mygroup, MYPORT)) time.sleep(1) @@ -53,7 +53,7 @@ def receiver(): while 1: data, sender = s.recvfrom(1500) while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's - print sender, ':', `data` + print sender, ':', repr(data) # Open a UDP socket, bind it to a port and select a multicast group diff --git a/Demo/sockets/radio.py b/Demo/sockets/radio.py index 6131d40..b68a4ec 100755 --- a/Demo/sockets/radio.py +++ b/Demo/sockets/radio.py @@ -10,5 +10,5 @@ s.bind(('', MYPORT)) while 1: data, wherefrom = s.recvfrom(1500, 0) - sys.stderr.write(`wherefrom` + '\n') + sys.stderr.write(repr(wherefrom) + '\n') sys.stdout.write(data) diff --git a/Demo/sockets/telnet.py b/Demo/sockets/telnet.py index ee7c43b..d86cbeb 100755 --- a/Demo/sockets/telnet.py +++ b/Demo/sockets/telnet.py @@ -53,7 +53,7 @@ def main(): try: s.connect((host, port)) except error, msg: - sys.stderr.write('connect failed: ' + `msg` + '\n') + sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # pid = posix.fork() diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py index 4410165..720cfe1 100755 --- a/Demo/sockets/udpecho.py +++ b/Demo/sockets/udpecho.py @@ -37,7 +37,7 @@ def server(): print 'udp echo server ready' while 1: data, addr = s.recvfrom(BUFSIZE) - print 'server received', `data`, 'from', `addr` + print 'server received %r from %r' % (data, addr) s.sendto(data, addr) def client(): @@ -58,6 +58,6 @@ def client(): break s.sendto(line, addr) data, fromaddr = s.recvfrom(BUFSIZE) - print 'client received', `data`, 'from', `fromaddr` + print 'client received %r from %r' % (data, fromaddr) main() diff --git a/Demo/sockets/unicast.py b/Demo/sockets/unicast.py index 1e9caeb..0a30f35 100644 --- a/Demo/sockets/unicast.py +++ b/Demo/sockets/unicast.py @@ -9,7 +9,7 @@ s = socket(AF_INET, SOCK_DGRAM) s.bind(('', 0)) while 1: - data = `time.time()` + '\n' + data = repr(time.time()) + '\n' s.sendto(data, ('', MYPORT)) time.sleep(2) diff --git a/Demo/sockets/unixclient.py b/Demo/sockets/unixclient.py index a0d80f6..cccd617 100644 --- a/Demo/sockets/unixclient.py +++ b/Demo/sockets/unixclient.py @@ -7,4 +7,4 @@ s.connect(FILE) s.send('Hello, world') data = s.recv(1024) s.close() -print 'Received', `data` +print 'Received', repr(data) diff --git a/Demo/threads/Coroutine.py b/Demo/threads/Coroutine.py index 0cf9255..4cc65f7 100644 --- a/Demo/threads/Coroutine.py +++ b/Demo/threads/Coroutine.py @@ -138,10 +138,9 @@ class Coroutine: def tran(self, target, data=None): if not self.invokedby.has_key(target): - raise TypeError, '.tran target ' + `target` + \ - ' is not an active coroutine' + raise TypeError, '.tran target %r is not an active coroutine' % (target,) if self.killed: - raise TypeError, '.tran target ' + `target` + ' is killed' + raise TypeError, '.tran target %r is killed' % (target,) self.value = data me = self.active self.invokedby[target] = me @@ -153,7 +152,7 @@ class Coroutine: if self.main is not me: raise Killed if self.terminated_by is not None: - raise EarlyExit, `self.terminated_by` + ' terminated early' + raise EarlyExit, '%r terminated early' % (self.terminated_by,) return self.value diff --git a/Demo/threads/find.py b/Demo/threads/find.py index ab581e3..7d5edc1 100644 --- a/Demo/threads/find.py +++ b/Demo/threads/find.py @@ -116,7 +116,7 @@ def main(): wq.run(nworkers) t2 = time.time() - sys.stderr.write('Total time ' + `t2-t1` + ' sec.\n') + sys.stderr.write('Total time %r sec.\n' % (t2-t1)) # The predicate -- defines what files we look for. @@ -133,7 +133,7 @@ def find(dir, pred, wq): try: names = os.listdir(dir) except os.error, msg: - print `dir`, ':', msg + print repr(dir), ':', msg return for name in names: if name not in (os.curdir, os.pardir): @@ -141,7 +141,7 @@ def find(dir, pred, wq): try: stat = os.lstat(fullname) except os.error, msg: - print `fullname`, ':', msg + print repr(fullname), ':', msg continue if pred(dir, name, fullname, stat): print fullname diff --git a/Demo/threads/sync.py b/Demo/threads/sync.py index a8556c4..1688403 100644 --- a/Demo/threads/sync.py +++ b/Demo/threads/sync.py @@ -336,7 +336,7 @@ class condition: def broadcast(self, num = -1): if num < -1: - raise ValueError, '.broadcast called with num ' + `num` + raise ValueError, '.broadcast called with num %r' % (num,) if num == 0: return self.idlock.acquire() @@ -418,7 +418,7 @@ class semaphore: self.nonzero.acquire() if self.count == self.maxcount: raise ValueError, '.v() tried to raise semaphore count above ' \ - 'initial value ' + `maxcount` + 'initial value %r' % (maxcount,)) self.count = self.count + 1 self.nonzero.signal() self.nonzero.release() diff --git a/Demo/threads/telnet.py b/Demo/threads/telnet.py index 3c70cb0..707a353 100644 --- a/Demo/threads/telnet.py +++ b/Demo/threads/telnet.py @@ -57,7 +57,7 @@ def main(): try: s.connect((host, port)) except error, msg: - sys.stderr.write('connect failed: ' + `msg` + '\n') + sys.stderr.write('connect failed: %r\n' % (msg,)) sys.exit(1) # thread.start_new(child, (s,)) @@ -77,7 +77,7 @@ def parent(s): for c in data: if opt: print ord(c) -## print '(replying: ' + `opt+c` + ')' +## print '(replying: %r)' % (opt+c,) s.send(opt + c) opt = '' elif iac: @@ -101,13 +101,13 @@ def parent(s): cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush() -## print 'Out:', `cleandata` +## print 'Out:', repr(cleandata) def child(s): # read stdin, write socket while 1: line = sys.stdin.readline() -## print 'Got:', `line` +## print 'Got:', repr(line) if not line: break s.send(line) diff --git a/Demo/tix/samples/DirList.py b/Demo/tix/samples/DirList.py index b2aad33..8d7536c 100755 --- a/Demo/tix/samples/DirList.py +++ b/Demo/tix/samples/DirList.py @@ -75,7 +75,7 @@ class DemoDirList: top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \ self.copy_name(dir,ent) - # top.ent.entry.insert(0,'tix'+`self`) + # top.ent.entry.insert(0,'tix'+repr(self)) top.ent.entry.bind('', lambda self=self: self.okcmd () ) top.pack( expand='yes', fill='both', side=TOP) diff --git a/Demo/tkinter/guido/mbox.py b/Demo/tkinter/guido/mbox.py index 9aea7ee..6d7a410 100755 --- a/Demo/tkinter/guido/mbox.py +++ b/Demo/tkinter/guido/mbox.py @@ -253,7 +253,7 @@ def refile_message(e=None): def fixfocus(near, itop): n = scanbox.size() for i in range(n): - line = scanbox.get(`i`) + line = scanbox.get(repr(i)) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) if num >= near: diff --git a/Demo/tkinter/guido/solitaire.py b/Demo/tkinter/guido/solitaire.py index bd7328d..a205afd 100755 --- a/Demo/tkinter/guido/solitaire.py +++ b/Demo/tkinter/guido/solitaire.py @@ -183,7 +183,7 @@ class Card: def __repr__(self): """Return a string for debug print statements.""" - return "Card(%s, %s)" % (`self.suit`, `self.value`) + return "Card(%r, %r)" % (self.suit, self.value) def moveto(self, x, y): """Move the card to absolute position (x, y).""" diff --git a/Demo/tkinter/matt/animation-w-velocity-ctrl.py b/Demo/tkinter/matt/animation-w-velocity-ctrl.py index a45f3f0..f3332f2 100644 --- a/Demo/tkinter/matt/animation-w-velocity-ctrl.py +++ b/Demo/tkinter/matt/animation-w-velocity-ctrl.py @@ -28,7 +28,7 @@ class Test(Frame): def moveThing(self, *args): velocity = self.speed.get() str = float(velocity) / 1000.0 - str = `str` + "i" + str = "%ri" % (str,) self.draw.move("thing", str, str) self.after(10, self.moveThing) diff --git a/Demo/tkinter/matt/pong-demo-1.py b/Demo/tkinter/matt/pong-demo-1.py index dacaa38..a27f334 100644 --- a/Demo/tkinter/matt/pong-demo-1.py +++ b/Demo/tkinter/matt/pong-demo-1.py @@ -39,7 +39,7 @@ class Pong(Frame): self.x = self.x + deltax self.y = self.y + deltay - self.draw.move(self.ball, `deltax` + "i", `deltay` + "i") + self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay) self.after(10, self.moveBall) def __init__(self, master=None): diff --git a/Doc/lib/caseless.py b/Doc/lib/caseless.py index 107fed6..b128219 100755 --- a/Doc/lib/caseless.py +++ b/Doc/lib/caseless.py @@ -47,10 +47,10 @@ if __name__ == "__main__": print "not ok: no conflict between -h and -H" parser.add_option("-f", "--file", dest="file") - #print `parser.get_option("-f")` - #print `parser.get_option("-F")` - #print `parser.get_option("--file")` - #print `parser.get_option("--fIlE")` + #print repr(parser.get_option("-f")) + #print repr(parser.get_option("-F")) + #print repr(parser.get_option("--file")) + #print repr(parser.get_option("--fIlE")) (options, args) = parser.parse_args(["--FiLe", "foo"]) assert options.file == "foo", options.file print "ok: case insensitive long options work" diff --git a/Doc/tools/cvsinfo.py b/Doc/tools/cvsinfo.py index 58a32c2..cc90fe5 100644 --- a/Doc/tools/cvsinfo.py +++ b/Doc/tools/cvsinfo.py @@ -78,4 +78,4 @@ class RepositoryInfo: return fn[len(self.cvsroot_path)+1:] def __repr__(self): - return "" % `self.get_cvsroot()` + return "" % self.get_cvsroot() diff --git a/Doc/tools/refcounts.py b/Doc/tools/refcounts.py index d82def7..ccfc8c6 100644 --- a/Doc/tools/refcounts.py +++ b/Doc/tools/refcounts.py @@ -32,7 +32,7 @@ def loadfile(fp): continue parts = line.split(":", 4) if len(parts) != 5: - raise ValueError("Not enough fields in " + `line`) + raise ValueError("Not enough fields in %r" % line) function, type, arg, refcount, comment = parts if refcount == "null": refcount = None diff --git a/Doc/tools/sgmlconv/esistools.py b/Doc/tools/sgmlconv/esistools.py index b9c029b..833fea1 100644 --- a/Doc/tools/sgmlconv/esistools.py +++ b/Doc/tools/sgmlconv/esistools.py @@ -29,7 +29,7 @@ def decode(s): n, s = s.split(";", 1) r = r + unichr(int(n)) else: - raise ValueError, "can't handle " + `s` + raise ValueError, "can't handle %r" % s return r @@ -220,8 +220,8 @@ class ESISReader(xml.sax.xmlreader.XMLReader): return self._decl_handler else: - raise xml.sax.SAXNotRecognizedException("unknown property %s" - % `property`) + raise xml.sax.SAXNotRecognizedException("unknown property %r" + % (property, )) def setProperty(self, property, value): if property == xml.sax.handler.property_lexical_handler: diff --git a/Doc/tools/sgmlconv/latex2esis.py b/Doc/tools/sgmlconv/latex2esis.py index 47739a6..b30aaa5 100755 --- a/Doc/tools/sgmlconv/latex2esis.py +++ b/Doc/tools/sgmlconv/latex2esis.py @@ -73,8 +73,8 @@ def popping(name, point, depth): class _Stack(list): def append(self, entry): if not isinstance(entry, str): - raise LaTeXFormatError("cannot push non-string on stack: " - + `entry`) + raise LaTeXFormatError("cannot push non-string on stack: %r" + % (entry, )) #dbgmsg("%s<%s>" % (" "*len(self.data), entry)) list.append(self, entry) @@ -208,8 +208,8 @@ class Conversion: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( - "could not extract parameter %s for %s: %s" - % (pentry.name, macroname, `line[:100]`)) + "could not extract parameter %s for %s: %r" + % (pentry.name, macroname, line[:100])) if entry.outputname: self.dump_attr(pentry, m.group(1)) line = line[m.end():] @@ -259,7 +259,7 @@ class Conversion: opened = 1 stack.append(entry.name) self.write("(%s\n" % entry.outputname) - #dbgmsg("--- text: %s" % `pentry.text`) + #dbgmsg("--- text: %r" % pentry.text) self.write("-%s\n" % encode(pentry.text)) elif pentry.type == "entityref": self.write("&%s\n" % pentry.name) @@ -326,8 +326,8 @@ class Conversion: extra = "" if len(line) > 100: extra = "..." - raise LaTeXFormatError("could not identify markup: %s%s" - % (`line[:100]`, extra)) + raise LaTeXFormatError("could not identify markup: %r%s" + % (line[:100], extra)) while stack: entry = self.get_entry(stack[-1]) if entry.closes: @@ -361,7 +361,7 @@ class Conversion: def get_entry(self, name): entry = self.table.get(name) if entry is None: - dbgmsg("get_entry(%s) failing; building default entry!" % `name`) + dbgmsg("get_entry(%r) failing; building default entry!" % (name, )) # not defined; build a default entry: entry = TableEntry(name) entry.has_content = 1 @@ -486,7 +486,7 @@ class TableHandler(xml.sax.handler.ContentHandler): def end_macro(self): name = self.__current.name if self.__table.has_key(name): - raise ValueError("name %s already in use" % `name`) + raise ValueError("name %r already in use" % (name,)) self.__table[name] = self.__current self.__current = None diff --git a/Lib/BaseHTTPServer.py b/Lib/BaseHTTPServer.py index 15e7525..27ac513 100644 --- a/Lib/BaseHTTPServer.py +++ b/Lib/BaseHTTPServer.py @@ -238,7 +238,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): if len(words) == 3: [command, path, version] = words if version[:5] != 'HTTP/': - self.send_error(400, "Bad request version (%s)" % `version`) + self.send_error(400, "Bad request version (%r)" % version) return False try: base_version_number = version.split('/', 1)[1] @@ -253,7 +253,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): raise ValueError version_number = int(version_number[0]), int(version_number[1]) except (ValueError, IndexError): - self.send_error(400, "Bad request version (%s)" % `version`) + self.send_error(400, "Bad request version (%r)" % version) return False if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": self.close_connection = 0 @@ -266,12 +266,12 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): self.close_connection = 1 if command != 'GET': self.send_error(400, - "Bad HTTP/0.9 request type (%s)" % `command`) + "Bad HTTP/0.9 request type (%r)" % command) return False elif not words: return False else: - self.send_error(400, "Bad request syntax (%s)" % `requestline`) + self.send_error(400, "Bad request syntax (%r)" % requestline) return False self.command, self.path, self.request_version = command, path, version @@ -302,7 +302,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): return mname = 'do_' + self.command if not hasattr(self, mname): - self.send_error(501, "Unsupported method (%s)" % `self.command`) + self.send_error(501, "Unsupported method (%r)" % self.command) return method = getattr(self, mname) method() diff --git a/Lib/Bastion.py b/Lib/Bastion.py index ae2db74..58cce97 100644 --- a/Lib/Bastion.py +++ b/Lib/Bastion.py @@ -124,7 +124,7 @@ def Bastion(object, filter = lambda name: name[:1] != '_', return get1(name) if name is None: - name = `object` + name = repr(object) return bastionclass(get2, name) diff --git a/Lib/CGIHTTPServer.py b/Lib/CGIHTTPServer.py index 7f481b7..52e04e9 100644 --- a/Lib/CGIHTTPServer.py +++ b/Lib/CGIHTTPServer.py @@ -117,21 +117,21 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): - self.send_error(404, "No such CGI script (%s)" % `scriptname`) + self.send_error(404, "No such CGI script (%r)" % scriptname) return if not os.path.isfile(scriptfile): - self.send_error(403, "CGI script is not a plain file (%s)" % - `scriptname`) + self.send_error(403, "CGI script is not a plain file (%r)" % + scriptname) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2 or self.have_popen3): - self.send_error(403, "CGI script is not a Python script (%s)" % - `scriptname`) + self.send_error(403, "CGI script is not a Python script (%r)" % + scriptname) return if not self.is_executable(scriptfile): - self.send_error(403, "CGI script is not executable (%s)" % - `scriptname`) + self.send_error(403, "CGI script is not executable (%r)" % + scriptname) return # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html diff --git a/Lib/ConfigParser.py b/Lib/ConfigParser.py index d98993a..e12717d 100644 --- a/Lib/ConfigParser.py +++ b/Lib/ConfigParser.py @@ -118,7 +118,7 @@ class NoSectionError(Error): """Raised when no section matches a requested option.""" def __init__(self, section): - Error.__init__(self, 'No section: ' + `section`) + Error.__init__(self, 'No section: %r' % (section,)) self.section = section class DuplicateSectionError(Error): @@ -191,7 +191,7 @@ class MissingSectionHeaderError(ParsingError): def __init__(self, filename, lineno, line): Error.__init__( self, - 'File contains no section headers.\nfile: %s, line: %d\n%s' % + 'File contains no section headers.\nfile: %s, line: %d\n%r' % (filename, lineno, line)) self.filename = filename self.lineno = lineno @@ -453,7 +453,7 @@ class RawConfigParser: optname = None # no section header in the file? elif cursect is None: - raise MissingSectionHeaderError(fpname, lineno, `line`) + raise MissingSectionHeaderError(fpname, lineno, line) # an option line? else: mo = self.OPTCRE.match(line) @@ -478,7 +478,7 @@ class RawConfigParser: # list of all bogus lines if not e: e = ParsingError(fpname) - e.append(lineno, `line`) + e.append(lineno, repr(line)) # if any parsing errors occurred, raise an exception if e: raise e @@ -613,4 +613,4 @@ class SafeConfigParser(ConfigParser): else: raise InterpolationSyntaxError( option, section, - "'%' must be followed by '%' or '(', found: " + `rest`) + "'%%' must be followed by '%%' or '(', found: %r" % (rest,)) diff --git a/Lib/HTMLParser.py b/Lib/HTMLParser.py index c082fde..7334581 100644 --- a/Lib/HTMLParser.py +++ b/Lib/HTMLParser.py @@ -272,8 +272,8 @@ class HTMLParser(markupbase.ParserBase): - self.__starttag_text.rfind("\n") else: offset = offset + len(self.__starttag_text) - self.error("junk characters in start tag: %s" - % `rawdata[k:endpos][:20]`) + self.error("junk characters in start tag: %r" + % (rawdata[k:endpos][:20],)) if end.endswith('/>'): # XHTML-style empty tag: self.handle_startendtag(tag, attrs) @@ -324,7 +324,7 @@ class HTMLParser(markupbase.ParserBase): j = match.end() match = endtagfind.match(rawdata, i) # if not match: - self.error("bad end tag: %s" % `rawdata[i:j]`) + self.error("bad end tag: %r" % (rawdata[i:j],)) tag = match.group(1) self.handle_endtag(tag.lower()) self.clear_cdata_mode() @@ -368,7 +368,7 @@ class HTMLParser(markupbase.ParserBase): pass def unknown_decl(self, data): - self.error("unknown declaration: " + `data`) + self.error("unknown declaration: %r" % (data,)) # Internal -- helper to remove special character quoting def unescape(self, s): diff --git a/Lib/StringIO.py b/Lib/StringIO.py index 4739d13..f35054e 100644 --- a/Lib/StringIO.py +++ b/Lib/StringIO.py @@ -222,10 +222,10 @@ def test(): f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print 'First line =', `f.readline()` + print 'First line =', repr(f.readline()) print 'Position =', f.tell() line = f.readline() - print 'Second line =', `line` + print 'Second line =', repr(line) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: diff --git a/Lib/aifc.py b/Lib/aifc.py index 0275e42..781d77c 100644 --- a/Lib/aifc.py +++ b/Lib/aifc.py @@ -392,7 +392,7 @@ class Aifc_read: for marker in self._markers: if id == marker[0]: return marker - raise Error, 'marker ' + `id` + ' does not exist' + raise Error, 'marker %r does not exist' % (id,) def setpos(self, pos): if pos < 0 or pos > self._nframes: @@ -697,7 +697,7 @@ class Aifc_write: for marker in self._markers: if id == marker[0]: return marker - raise Error, 'marker ' + `id` + ' does not exist' + raise Error, 'marker %r does not exist' % (id,) def getmarkers(self): if len(self._markers) == 0: diff --git a/Lib/atexit.py b/Lib/atexit.py index 59d5cf3..85ccb24 100644 --- a/Lib/atexit.py +++ b/Lib/atexit.py @@ -40,9 +40,9 @@ if __name__ == "__main__": def x1(): print "running x1" def x2(n): - print "running x2(%s)" % `n` + print "running x2(%r)" % (n,) def x3(n, kwd=None): - print "running x3(%s, kwd=%s)" % (`n`, `kwd`) + print "running x3(%r, kwd=%r)" % (n, kwd) register(x1) register(x2, 12) diff --git a/Lib/base64.py b/Lib/base64.py index 54ee623..f90b91d 100755 --- a/Lib/base64.py +++ b/Lib/base64.py @@ -348,7 +348,7 @@ def test1(): s0 = "Aladdin:open sesame" s1 = encodestring(s0) s2 = decodestring(s1) - print s0, `s1`, s2 + print s0, repr(s1), s2 if __name__ == '__main__': diff --git a/Lib/bdb.py b/Lib/bdb.py index 45e9d03..11ed212 100644 --- a/Lib/bdb.py +++ b/Lib/bdb.py @@ -52,7 +52,7 @@ class Bdb: return self.dispatch_return(frame, arg) if event == 'exception': return self.dispatch_exception(frame, arg) - print 'bdb.Bdb.dispatch: unknown debugging event:', `event` + print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event) return self.trace_dispatch def dispatch_line(self, frame): @@ -311,7 +311,7 @@ class Bdb: import linecache, repr frame, lineno = frame_lineno filename = self.canonic(frame.f_code.co_filename) - s = filename + '(' + `lineno` + ')' + s = '%s(%r)' % (filename, lineno) if frame.f_code.co_name: s = s + frame.f_code.co_name else: diff --git a/Lib/binhex.py b/Lib/binhex.py index 5700659..9735f2e 100644 --- a/Lib/binhex.py +++ b/Lib/binhex.py @@ -229,7 +229,7 @@ class BinHex: def close_data(self): if self.dlen != 0: - raise Error, 'Incorrect data size, diff='+`self.rlen` + raise Error, 'Incorrect data size, diff=%r' % (self.rlen,) self._writecrc() self.state = _DID_DATA @@ -248,7 +248,7 @@ class BinHex: raise Error, 'Close at the wrong time' if self.rlen != 0: raise Error, \ - "Incorrect resource-datasize, diff="+`self.rlen` + "Incorrect resource-datasize, diff=%r" % (self.rlen,) self._writecrc() self.ofp.close() self.state = None diff --git a/Lib/bsddb/dbrecio.py b/Lib/bsddb/dbrecio.py index 470fb41..22e382a 100644 --- a/Lib/bsddb/dbrecio.py +++ b/Lib/bsddb/dbrecio.py @@ -164,10 +164,10 @@ def _test(): f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print 'First line =', `f.readline()` + print 'First line =', repr(f.readline()) here = f.tell() line = f.readline() - print 'Second line =', `line` + print 'Second line =', repr(line) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: diff --git a/Lib/bsddb/dbtables.py b/Lib/bsddb/dbtables.py index 6edfd29..e1d2c43 100644 --- a/Lib/bsddb/dbtables.py +++ b/Lib/bsddb/dbtables.py @@ -206,7 +206,7 @@ class bsdTableDB : try: key, data = cur.first() while 1: - print `{key: data}` + print repr({key: data}) next = cur.next() if next: key, data = next @@ -341,9 +341,9 @@ class bsdTableDB : try: tcolpickles = self.db.get(_columns_key(table)) except DBNotFoundError: - raise TableDBError, "unknown table: " + `table` + raise TableDBError, "unknown table: %r" % (table,) if not tcolpickles: - raise TableDBError, "unknown table: " + `table` + raise TableDBError, "unknown table: %r" % (table,) self.__tablecolumns[table] = pickle.loads(tcolpickles) def __new_rowid(self, table, txn) : @@ -384,7 +384,7 @@ class bsdTableDB : self.__load_column_info(table) for column in rowdict.keys() : if not self.__tablecolumns[table].count(column): - raise TableDBError, "unknown column: "+`column` + raise TableDBError, "unknown column: %r" % (column,) # get a unique row identifier for this row txn = self.env.txn_begin() @@ -535,7 +535,7 @@ class bsdTableDB : columns = self.tablecolumns[table] for column in (columns + conditions.keys()): if not self.__tablecolumns[table].count(column): - raise TableDBError, "unknown column: "+`column` + raise TableDBError, "unknown column: %r" % (column,) # keyed on rows that match so far, containings dicts keyed on # column names containing the data for that row and column. diff --git a/Lib/bsddb/test/test_associate.py b/Lib/bsddb/test/test_associate.py index f810eb0..fc92c22 100644 --- a/Lib/bsddb/test/test_associate.py +++ b/Lib/bsddb/test/test_associate.py @@ -200,7 +200,7 @@ class AssociateTestCase(unittest.TestCase): def getGenre(self, priKey, priData): assert type(priData) == type("") if verbose: - print 'getGenre key:', `priKey`, 'data:', `priData` + print 'getGenre key: %r data: %r' % (priKey, priData) genre = string.split(priData, '|')[2] if genre == 'Blues': return db.DB_DONOTINDEX @@ -242,7 +242,7 @@ class ShelveAssociateTestCase(AssociateTestCase): def getGenre(self, priKey, priData): assert type(priData) == type(()) if verbose: - print 'getGenre key:', `priKey`, 'data:', `priData` + print 'getGenre key: %r data: %r' % (priKey, priData) genre = priData[2] if genre == 'Blues': return db.DB_DONOTINDEX diff --git a/Lib/bsddb/test/test_basics.py b/Lib/bsddb/test/test_basics.py index d757b34..da7e18f 100644 --- a/Lib/bsddb/test/test_basics.py +++ b/Lib/bsddb/test/test_basics.py @@ -361,7 +361,7 @@ class BasicTestCase(unittest.TestCase): if set_raises_error: self.fail("expected exception") if n != None: - self.fail("expected None: "+`n`) + self.fail("expected None: %r" % (n,)) rec = c.get_both('0404', self.makeData('0404')) assert rec == ('0404', self.makeData('0404')) @@ -375,7 +375,7 @@ class BasicTestCase(unittest.TestCase): if get_raises_error: self.fail("expected exception") if n != None: - self.fail("expected None: "+`n`) + self.fail("expected None: %r" % (n,)) if self.d.get_type() == db.DB_BTREE: rec = c.set_range('011') @@ -548,7 +548,7 @@ class BasicTestCase(unittest.TestCase): num = d.truncate() assert num >= 1, "truncate returned <= 0 on non-empty database" num = d.truncate() - assert num == 0, "truncate on empty DB returned nonzero (%s)" % `num` + assert num == 0, "truncate on empty DB returned nonzero (%r)" % (num,) #---------------------------------------------------------------------- @@ -674,7 +674,7 @@ class BasicTransactionTestCase(BasicTestCase): num = d.truncate(txn) assert num >= 1, "truncate returned <= 0 on non-empty database" num = d.truncate(txn) - assert num == 0, "truncate on empty DB returned nonzero (%s)" % `num` + assert num == 0, "truncate on empty DB returned nonzero (%r)" % (num,) txn.commit() #---------------------------------------- diff --git a/Lib/bsddb/test/test_dbtables.py b/Lib/bsddb/test/test_dbtables.py index eb5758f..1128a5a 100644 --- a/Lib/bsddb/test/test_dbtables.py +++ b/Lib/bsddb/test/test_dbtables.py @@ -109,7 +109,7 @@ class TableDBTestCase(unittest.TestCase): assert values[1]['Species'] == 'Penguin' else : if verbose: - print "values=", `values` + print "values= %r" % (values,) raise "Wrong values returned!" def test03(self): diff --git a/Lib/calendar.py b/Lib/calendar.py index fb56826..321059d 100644 --- a/Lib/calendar.py +++ b/Lib/calendar.py @@ -151,9 +151,9 @@ def month(theyear, themonth, w=0, l=0): """Return a month's calendar string (multi-line).""" w = max(2, w) l = max(1, l) - s = ((month_name[themonth] + ' ' + `theyear`).center( - 7 * (w + 1) - 1).rstrip() + - '\n' * l + weekheader(w).rstrip() + '\n' * l) + s = ("%s %r" % (month_name[themonth], theyear)).center( + 7 * (w + 1) - 1).rstrip() + \ + '\n' * l + weekheader(w).rstrip() + '\n' * l for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n' @@ -181,7 +181,7 @@ def calendar(year, w=0, l=0, c=_spacing): l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 - s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l + s = repr(year).center(colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): diff --git a/Lib/cgi.py b/Lib/cgi.py index ac7192b..2576e75 100755 --- a/Lib/cgi.py +++ b/Lib/cgi.py @@ -212,7 +212,7 @@ def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): nv = name_value.split('=', 1) if len(nv) != 2: if strict_parsing: - raise ValueError, "bad query field: %s" % `name_value` + raise ValueError, "bad query field: %r" % (name_value,) continue if len(nv[1]) or keep_blank_values: name = urllib.unquote(nv[0].replace('+', ' ')) @@ -247,8 +247,8 @@ def parse_multipart(fp, pdict): if 'boundary' in pdict: boundary = pdict['boundary'] if not valid_boundary(boundary): - raise ValueError, ('Invalid boundary in multipart form: %s' - % `boundary`) + raise ValueError, ('Invalid boundary in multipart form: %r' + % (boundary,)) nextpart = "--" + boundary lastpart = "--" + boundary + "--" @@ -361,7 +361,7 @@ class MiniFieldStorage: def __repr__(self): """Return printable representation.""" - return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`) + return "MiniFieldStorage(%r, %r)" % (self.name, self.value) class FieldStorage: @@ -522,8 +522,8 @@ class FieldStorage: def __repr__(self): """Return a printable representation.""" - return "FieldStorage(%s, %s, %s)" % ( - `self.name`, `self.filename`, `self.value`) + return "FieldStorage(%r, %r, %r)" % ( + self.name, self.filename, self.value) def __iter__(self): return iter(self.keys()) @@ -632,8 +632,7 @@ class FieldStorage: """Internal: read a part that is itself multipart.""" ib = self.innerboundary if not valid_boundary(ib): - raise ValueError, ('Invalid boundary in multipart form: %s' - % `ib`) + raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,) self.list = [] klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, ib, @@ -957,8 +956,8 @@ def print_form(form): for key in keys: print "
" + escape(key) + ":", value = form[key] - print "" + escape(`type(value)`) + "" - print "
" + escape(`value`) + print "" + escape(repr(type(value))) + "" + print "
" + escape(repr(value)) print "" print diff --git a/Lib/difflib.py b/Lib/difflib.py index 699845c..c074b19 100644 --- a/Lib/difflib.py +++ b/Lib/difflib.py @@ -689,9 +689,9 @@ def get_close_matches(word, possibilities, n=3, cutoff=0.6): """ if not n > 0: - raise ValueError("n must be > 0: " + `n`) + raise ValueError("n must be > 0: %r" % (n,)) if not 0.0 <= cutoff <= 1.0: - raise ValueError("cutoff must be in [0.0, 1.0]: " + `cutoff`) + raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,)) result = [] s = SequenceMatcher() s.set_seq2(word) @@ -876,7 +876,7 @@ class Differ: elif tag == 'equal': g = self._dump(' ', a, alo, ahi) else: - raise ValueError, 'unknown tag ' + `tag` + raise ValueError, 'unknown tag %r' % (tag,) for line in g: yield line @@ -988,7 +988,7 @@ class Differ: atags += ' ' * la btags += ' ' * lb else: - raise ValueError, 'unknown tag ' + `tag` + raise ValueError, 'unknown tag %r' % (tag,) for line in self._qformat(aelt, belt, atags, btags): yield line else: diff --git a/Lib/dis.py b/Lib/dis.py index 3208011..5a74b3a 100644 --- a/Lib/dis.py +++ b/Lib/dis.py @@ -80,7 +80,7 @@ def disassemble(co, lasti=-1): else: print ' ', if i in labels: print '>>', else: print ' ', - print `i`.rjust(4), + print repr(i).rjust(4), print opname[op].ljust(20), i = i+1 if op >= HAVE_ARGUMENT: @@ -89,13 +89,13 @@ def disassemble(co, lasti=-1): i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536L - print `oparg`.rjust(5), + print repr(oparg).rjust(5), if op in hasconst: - print '(' + `co.co_consts[oparg]` + ')', + print '(' + repr(co.co_consts[oparg]) + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: - print '(to ' + `i + oparg` + ')', + print '(to ' + repr(i + oparg) + ')', elif op in haslocal: print '(' + co.co_varnames[oparg] + ')', elif op in hascompare: @@ -118,16 +118,16 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None, else: print ' ', if i in labels: print '>>', else: print ' ', - print `i`.rjust(4), + print repr(i).rjust(4), print opname[op].ljust(15), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 - print `oparg`.rjust(5), + print repr(oparg).rjust(5), if op in hasconst: if constants: - print '(' + `constants[oparg]` + ')', + print '(' + repr(constants[oparg]) + ')', else: print '(%d)'%oparg, elif op in hasname: @@ -136,7 +136,7 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None, else: print '(%d)'%oparg, elif op in hasjrel: - print '(to ' + `i + oparg` + ')', + print '(to ' + repr(i + oparg) + ')', elif op in haslocal: if varnames: print '(' + varnames[oparg] + ')', diff --git a/Lib/distutils/cmd.py b/Lib/distutils/cmd.py index 6e44221..fef4939 100644 --- a/Lib/distutils/cmd.py +++ b/Lib/distutils/cmd.py @@ -253,8 +253,8 @@ class Command: if not ok: raise DistutilsOptionError, \ - "'%s' must be a list of strings (got %s)" % \ - (option, `val`) + "'%s' must be a list of strings (got %r)" % \ + (option, val) def _ensure_tested_string (self, option, tester, what, error_fmt, default=None): diff --git a/Lib/distutils/core.py b/Lib/distutils/core.py index a463272..eb41972 100644 --- a/Lib/distutils/core.py +++ b/Lib/distutils/core.py @@ -202,7 +202,7 @@ def run_setup (script_name, script_args=None, stop_after="run"): used to drive the Distutils. """ if stop_after not in ('init', 'config', 'commandline', 'run'): - raise ValueError, "invalid value for 'stop_after': %s" % `stop_after` + raise ValueError, "invalid value for 'stop_after': %r" % (stop_after,) global _setup_stop_after, _setup_distribution _setup_stop_after = stop_after diff --git a/Lib/distutils/dir_util.py b/Lib/distutils/dir_util.py index bd1ea0f..e479b62 100644 --- a/Lib/distutils/dir_util.py +++ b/Lib/distutils/dir_util.py @@ -33,7 +33,7 @@ def mkpath (name, mode=0777, verbose=0, dry_run=0): # Detect a common bug -- name is None if type(name) is not StringType: raise DistutilsInternalError, \ - "mkpath: 'name' must be a string (got %s)" % `name` + "mkpath: 'name' must be a string (got %r)" % (name,) # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py index d313e7d..f63ea97 100644 --- a/Lib/distutils/dist.py +++ b/Lib/distutils/dist.py @@ -525,9 +525,9 @@ class Distribution: func() else: raise DistutilsClassError( - "invalid help function %s for help option '%s': " + "invalid help function %r for help option '%s': " "must be a callable object (function, etc.)" - % (`func`, help_option)) + % (func, help_option)) if help_option_found: return diff --git a/Lib/distutils/fancy_getopt.py b/Lib/distutils/fancy_getopt.py index a4a4e79..512bc9b 100644 --- a/Lib/distutils/fancy_getopt.py +++ b/Lib/distutils/fancy_getopt.py @@ -162,7 +162,7 @@ class FancyGetopt: else: # the option table is part of the code, so simply # assert that it is correct - assert "invalid option tuple: %s" % `option` + assert "invalid option tuple: %r" % (option,) # Type- and value-check the option names if type(long) is not StringType or len(long) < 2: diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py index dc3183b..8c3c8df 100644 --- a/Lib/distutils/util.py +++ b/Lib/distutils/util.py @@ -285,7 +285,7 @@ def execute (func, args, msg=None, verbose=0, dry_run=0): print. """ if msg is None: - msg = "%s%s" % (func.__name__, `args`) + msg = "%s%r" % (func.__name__, args) if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' @@ -307,7 +307,7 @@ def strtobool (val): elif val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 else: - raise ValueError, "invalid truth value %s" % `val` + raise ValueError, "invalid truth value %r" % (val,) def byte_compile (py_files, @@ -394,11 +394,11 @@ files = [ script.write(string.join(map(repr, py_files), ",\n") + "]\n") script.write(""" -byte_compile(files, optimize=%s, force=%s, - prefix=%s, base_dir=%s, - verbose=%s, dry_run=0, +byte_compile(files, optimize=%r, force=%r, + prefix=%r, base_dir=%r, + verbose=%r, dry_run=0, direct=1) -""" % (`optimize`, `force`, `prefix`, `base_dir`, `verbose`)) +""" % (optimize, force, prefix, base_dir, verbose)) script.close() @@ -432,8 +432,8 @@ byte_compile(files, optimize=%s, force=%s, if prefix: if file[:len(prefix)] != prefix: raise ValueError, \ - ("invalid prefix: filename %s doesn't start with %s" - % (`file`, `prefix`)) + ("invalid prefix: filename %r doesn't start with %r" + % (file, prefix)) dfile = dfile[len(prefix):] if base_dir: dfile = os.path.join(base_dir, dfile) diff --git a/Lib/doctest.py b/Lib/doctest.py index caac691..5020684 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -334,8 +334,8 @@ def _extract_examples(s): continue lineno = i - 1 if line[j] != " ": - raise ValueError("line " + `lineno` + " of docstring lacks " - "blank after " + PS1 + ": " + line) + raise ValueError("line %r of docstring lacks blank after %s: %s" % + (lineno, PS1, line)) j = j + 1 blanks = m.group(1) nblanks = len(blanks) @@ -348,7 +348,7 @@ def _extract_examples(s): if m: if m.group(1) != blanks: raise ValueError("inconsistent leading whitespace " - "in line " + `i` + " of docstring: " + line) + "in line %r of docstring: %s" % (i, line)) i = i + 1 else: break @@ -367,7 +367,7 @@ def _extract_examples(s): while 1: if line[:nblanks] != blanks: raise ValueError("inconsistent leading whitespace " - "in line " + `i` + " of docstring: " + line) + "in line %r of docstring: %s" % (i, line)) expect.append(line[nblanks:]) i = i + 1 line = lines[i] @@ -475,7 +475,7 @@ def _run_examples_inner(out, fakeout, examples, globs, verbose, name, failures = failures + 1 out("*" * 65 + "\n") _tag_out(out, ("Failure in example", source)) - out("from line #" + `lineno` + " of " + name + "\n") + out("from line #%r of %s\n" % (lineno, name)) if state == FAIL: _tag_out(out, ("Expected", want or NADA), ("Got", got)) else: @@ -686,8 +686,7 @@ See doctest.testmod docs for the meaning of optionflags. if mod is None and globs is None: raise TypeError("Tester.__init__: must specify mod or globs") if mod is not None and not _ismodule(mod): - raise TypeError("Tester.__init__: mod must be a module; " + - `mod`) + raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,)) if globs is None: globs = mod.__dict__ self.globs = globs @@ -775,7 +774,7 @@ See doctest.testmod docs for the meaning of optionflags. name = object.__name__ except AttributeError: raise ValueError("Tester.rundoc: name must be given " - "when object.__name__ doesn't exist; " + `object`) + "when object.__name__ doesn't exist; %r" % (object,)) if self.verbose: print "Running", name + ".__doc__" f, t = run_docstring_examples(object, self.globs, self.verbose, name, @@ -893,8 +892,7 @@ See doctest.testmod docs for the meaning of optionflags. """ if not hasattr(d, "items"): - raise TypeError("Tester.rundict: d must support .items(); " + - `d`) + raise TypeError("Tester.rundict: d must support .items(); %r" % (d,)) f = t = 0 # Run the tests by alpha order of names, for consistency in # verbose-mode output. @@ -936,7 +934,7 @@ See doctest.testmod docs for the meaning of optionflags. else: raise TypeError("Tester.run__test__: values in " "dict must be strings, functions, methods, " - "or classes; " + `v`) + "or classes; %r" % (v,)) failures = failures + f tries = tries + t finally: @@ -1139,7 +1137,7 @@ def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, m = sys.modules.get('__main__') if not _ismodule(m): - raise TypeError("testmod: module required; " + `m`) + raise TypeError("testmod: module required; %r" % (m,)) if name is None: name = m.__name__ tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate, @@ -1153,7 +1151,7 @@ def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, if testdict: if not hasattr(testdict, "items"): raise TypeError("testmod: module.__test__ must support " - ".items(); " + `testdict`) + ".items(); %r" % (testdict,)) f, t = tester.run__test__(testdict, name + ".__test__") failures += f tries += t diff --git a/Lib/formatter.py b/Lib/formatter.py index 3868b1b..109d66c 100644 --- a/Lib/formatter.py +++ b/Lib/formatter.py @@ -325,22 +325,22 @@ class AbstractWriter(NullWriter): """ def new_alignment(self, align): - print "new_alignment(%s)" % `align` + print "new_alignment(%r)" % (align,) def new_font(self, font): - print "new_font(%s)" % `font` + print "new_font(%r)" % (font,) def new_margin(self, margin, level): - print "new_margin(%s, %d)" % (`margin`, level) + print "new_margin(%r, %d)" % (margin, level) def new_spacing(self, spacing): - print "new_spacing(%s)" % `spacing` + print "new_spacing(%r)" % (spacing,) def new_styles(self, styles): - print "new_styles(%s)" % `styles` + print "new_styles(%r)" % (styles,) def send_paragraph(self, blankline): - print "send_paragraph(%s)" % `blankline` + print "send_paragraph(%r)" % (blankline,) def send_line_break(self): print "send_line_break()" @@ -349,13 +349,13 @@ class AbstractWriter(NullWriter): print "send_hor_rule()" def send_label_data(self, data): - print "send_label_data(%s)" % `data` + print "send_label_data(%r)" % (data,) def send_flowing_data(self, data): - print "send_flowing_data(%s)" % `data` + print "send_flowing_data(%r)" % (data,) def send_literal_data(self, data): - print "send_literal_data(%s)" % `data` + print "send_literal_data(%r)" % (data,) class DumbWriter(NullWriter): diff --git a/Lib/fpformat.py b/Lib/fpformat.py index 7319e2a..0ae86a9 100644 --- a/Lib/fpformat.py +++ b/Lib/fpformat.py @@ -88,7 +88,7 @@ def fix(x, digs): """Format x as [-]ddd.ddd with 'digs' digits after the point and at least one digit before. If digs <= 0, the point is suppressed.""" - if type(x) != type(''): x = `x` + if type(x) != type(''): x = repr(x) try: sign, intpart, fraction, expo = extract(x) except NotANumber: @@ -104,7 +104,7 @@ def sci(x, digs): """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.""" - if type(x) != type(''): x = `x` + if type(x) != type(''): x = repr(x) sign, intpart, fraction, expo = extract(x) if not intpart: while fraction and fraction[0] == '0': @@ -126,7 +126,7 @@ def sci(x, digs): expo + len(intpart) - 1 s = sign + intpart if digs > 0: s = s + '.' + fraction - e = `abs(expo)` + e = repr(abs(expo)) e = '0'*(3-len(e)) + e if expo < 0: e = '-' + e else: e = '+' + e diff --git a/Lib/ftplib.py b/Lib/ftplib.py index d67a0aa..9486918 100644 --- a/Lib/ftplib.py +++ b/Lib/ftplib.py @@ -161,7 +161,7 @@ class FTP: while i > 5 and s[i-1] in '\r\n': i = i-1 s = s[:5] + '*'*(i-5) + s[i:] - return `s` + return repr(s) # Internal: send one line to the server, appending CRLF def putline(self, line): @@ -250,7 +250,7 @@ class FTP: port number. ''' hbytes = host.split('.') - pbytes = [`port/256`, `port%256`] + pbytes = [repr(port/256), repr(port%256)] bytes = hbytes + pbytes cmd = 'PORT ' + ','.join(bytes) return self.voidcmd(cmd) @@ -264,7 +264,7 @@ class FTP: af = 2 if af == 0: raise error_proto, 'unsupported address family' - fields = ['', `af`, host, `port`, ''] + fields = ['', repr(af), host, repr(port), ''] cmd = 'EPRT ' + '|'.join(fields) return self.voidcmd(cmd) @@ -397,7 +397,7 @@ class FTP: fp = conn.makefile('rb') while 1: line = fp.readline() - if self.debugging > 2: print '*retr*', `line` + if self.debugging > 2: print '*retr*', repr(line) if not line: break if line[-2:] == CRLF: diff --git a/Lib/gopherlib.py b/Lib/gopherlib.py index 03801d0..01eab0a 100644 --- a/Lib/gopherlib.py +++ b/Lib/gopherlib.py @@ -47,7 +47,7 @@ def type_to_name(gtype): _type_to_name_map[eval(name)] = name[2:] if gtype in _type_to_name_map: return _type_to_name_map[gtype] - return 'TYPE=' + `gtype` + return 'TYPE=%r' % (gtype,) # Names for characters and strings CRLF = '\r\n' @@ -113,7 +113,7 @@ def get_directory(f): gtype = line[0] parts = line[1:].split(TAB) if len(parts) < 4: - print '(Bad line from server:', `line`, ')' + print '(Bad line from server: %r)' % (line,) continue if len(parts) > 4: if parts[4:] != ['+']: @@ -198,7 +198,7 @@ def test(): for item in entries: print item else: data = get_binary(f) - print 'binary data:', len(data), 'bytes:', `data[:100]`[:40] + print 'binary data:', len(data), 'bytes:', repr(data[:100])[:40] # Run the test when run as script if __name__ == '__main__': diff --git a/Lib/gzip.py b/Lib/gzip.py index a5d4087..d51b7db 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -442,7 +442,7 @@ def _test(): g = sys.stdout else: if arg[-3:] != ".gz": - print "filename doesn't end in .gz:", `arg` + print "filename doesn't end in .gz:", repr(arg) continue f = open(arg, "rb") g = __builtin__.open(arg[:-3], "wb") diff --git a/Lib/idlelib/ColorDelegator.py b/Lib/idlelib/ColorDelegator.py index d72d90c..7b7be22 100644 --- a/Lib/idlelib/ColorDelegator.py +++ b/Lib/idlelib/ColorDelegator.py @@ -182,7 +182,7 @@ class ColorDelegator(Delegator): lines_to_get = min(lines_to_get * 2, 100) ok = "SYNC" in self.tag_names(next + "-1c") line = self.get(mark, next) - ##print head, "get", mark, next, "->", `line` + ##print head, "get", mark, next, "->", repr(line) if not line: return for tag in self.tagdefs.keys(): diff --git a/Lib/idlelib/EditorWindow.py b/Lib/idlelib/EditorWindow.py index 0f0961c..65ffe54 100644 --- a/Lib/idlelib/EditorWindow.py +++ b/Lib/idlelib/EditorWindow.py @@ -761,7 +761,7 @@ class EditorWindow: try: self.load_extension(name) except: - print "Failed to load extension", `name` + print "Failed to load extension", repr(name) import traceback traceback.print_exc() @@ -937,7 +937,7 @@ class EditorWindow: elif key == 'context_use_ps1': self.context_use_ps1 = value else: - raise KeyError, "bad option name: %s" % `key` + raise KeyError, "bad option name: %r" % (key,) # If ispythonsource and guess are true, guess a good value for # indentwidth based on file content (if possible), and if @@ -1071,7 +1071,7 @@ class EditorWindow: y = PyParse.Parser(self.indentwidth, self.tabwidth) for context in self.num_context_lines: startat = max(lno - context, 1) - startatindex = `startat` + ".0" + startatindex = repr(startat) + ".0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) bod = y.find_good_parse_start( @@ -1103,7 +1103,7 @@ class EditorWindow: else: self.reindent_to(y.compute_backslash_indent()) else: - assert 0, "bogus continuation type " + `c` + assert 0, "bogus continuation type %r" % (c,) return "break" # This line starts a brand new stmt; indent relative to @@ -1333,7 +1333,7 @@ class IndentSearcher: if self.finished: return "" i = self.i = self.i + 1 - mark = `i` + ".0" + mark = repr(i) + ".0" if self.text.compare(mark, ">=", "end"): return "" return self.text.get(mark, mark + " lineend+1c") diff --git a/Lib/idlelib/FileList.py b/Lib/idlelib/FileList.py index 4e08e70..198055a 100644 --- a/Lib/idlelib/FileList.py +++ b/Lib/idlelib/FileList.py @@ -35,7 +35,7 @@ class FileList: if os.path.isdir(filename): tkMessageBox.showerror( "Is A Directory", - "The path %s is a directory." % `filename`, + "The path %r is a directory." % (filename,), master=self.root) return None key = os.path.normcase(filename) @@ -46,7 +46,7 @@ class FileList: if not os.path.exists(filename): tkMessageBox.showinfo( "New File", - "Opening non-existent file %s" % `filename`, + "Opening non-existent file %r" % (filename,), master=self.root) if action is None: return self.EditorWindow(self, filename, key) @@ -102,7 +102,7 @@ class FileList: self.inversedict[conflict] = None tkMessageBox.showerror( "Name Conflict", - "You now have multiple edit windows open for %s" % `filename`, + "You now have multiple edit windows open for %r" % (filename,), master=self.root) self.dict[newkey] = edit self.inversedict[edit] = newkey diff --git a/Lib/idlelib/GrepDialog.py b/Lib/idlelib/GrepDialog.py index 79fad31..ab136bc 100644 --- a/Lib/idlelib/GrepDialog.py +++ b/Lib/idlelib/GrepDialog.py @@ -77,7 +77,7 @@ class GrepDialog(SearchDialogBase): list.sort() self.close() pat = self.engine.getpat() - print "Searching %s in %s ..." % (`pat`, path) + print "Searching %r in %s ..." % (pat, path) hits = 0 for fn in list: try: diff --git a/Lib/idlelib/ObjectBrowser.py b/Lib/idlelib/ObjectBrowser.py index 416be5a..a2a6cee 100644 --- a/Lib/idlelib/ObjectBrowser.py +++ b/Lib/idlelib/ObjectBrowser.py @@ -97,7 +97,7 @@ class SequenceTreeItem(ObjectTreeItem): continue def setfunction(value, key=key, object=self.object): object[key] = value - item = make_objecttreeitem(`key` + ":", value, setfunction) + item = make_objecttreeitem("%r:" % (key,), value, setfunction) sublist.append(item) return sublist diff --git a/Lib/idlelib/ParenMatch.py b/Lib/idlelib/ParenMatch.py index bd4e077..407f468 100644 --- a/Lib/idlelib/ParenMatch.py +++ b/Lib/idlelib/ParenMatch.py @@ -142,7 +142,7 @@ class LastOpenBracketFinder: y = PyParse.Parser(self.indentwidth, self.tabwidth) for context in self.num_context_lines: startat = max(lno - context, 1) - startatindex = `startat` + ".0" + startatindex = repr(startat) + ".0" # rawtext needs to contain everything up to the last # character, which was the close paren. the parser also # requires that the last line ends with "\n" diff --git a/Lib/idlelib/PyShell.py b/Lib/idlelib/PyShell.py index 0605285..c619b7f 100644 --- a/Lib/idlelib/PyShell.py +++ b/Lib/idlelib/PyShell.py @@ -335,9 +335,9 @@ class ModifiedInterpreter(InteractiveInterpreter): del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') if __name__ == 'idlelib.PyShell': - command = "__import__('idlelib.run').run.main(" + `del_exitf` +")" + command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,) else: - command = "__import__('run').main(" + `del_exitf` + ")" + command = "__import__('run').main(%r)" % (del_exitf,) if sys.platform[:3] == 'win' and ' ' in sys.executable: # handle embedded space in path by quoting the argument decorated_exec = '"%s"' % sys.executable @@ -454,12 +454,12 @@ class ModifiedInterpreter(InteractiveInterpreter): def transfer_path(self): self.runcommand("""if 1: import sys as _sys - _sys.path = %s + _sys.path = %r del _sys _msg = 'Use File/Exit or your end-of-file key to quit IDLE' __builtins__.quit = __builtins__.exit = _msg del _msg - \n""" % `sys.path`) + \n""" % (sys.path,)) active_seq = None @@ -483,7 +483,7 @@ class ModifiedInterpreter(InteractiveInterpreter): console = self.tkconsole.console if how == "OK": if what is not None: - print >>console, `what` + print >>console, repr(what) elif how == "EXCEPTION": if self.tkconsole.getvar("<>"): self.remote_stack_viewer() @@ -589,14 +589,14 @@ class ModifiedInterpreter(InteractiveInterpreter): def prepend_syspath(self, filename): "Prepend sys.path with file's directory if not already included" self.runcommand("""if 1: - _filename = %s + _filename = %r import sys as _sys from os.path import dirname as _dirname _dir = _dirname(_filename) if not _dir in _sys.path: _sys.path.insert(0, _dir) del _filename, _sys, _dirname, _dir - \n""" % `filename`) + \n""" % (filename,)) def showsyntaxerror(self, filename=None): """Extend base class method: Add Colorizing @@ -1333,9 +1333,9 @@ def main(): if shell and cmd or script: shell.interp.runcommand("""if 1: import sys as _sys - _sys.argv = %s + _sys.argv = %r del _sys - \n""" % `sys.argv`) + \n""" % (sys.argv,)) if cmd: shell.interp.execsource(cmd) elif script: diff --git a/Lib/idlelib/RemoteDebugger.py b/Lib/idlelib/RemoteDebugger.py index bdcef51..74085c3 100644 --- a/Lib/idlelib/RemoteDebugger.py +++ b/Lib/idlelib/RemoteDebugger.py @@ -94,7 +94,7 @@ class IdbAdapter: self.idb.set_return(frame) def get_stack(self, fid, tbid): - ##print >>sys.__stderr__, "get_stack(%s, %s)" % (`fid`, `tbid`) + ##print >>sys.__stderr__, "get_stack(%r, %r)" % (fid, tbid) frame = frametable[fid] if tbid is None: tb = None @@ -295,7 +295,7 @@ class IdbProxy: def call(self, methodname, *args, **kwargs): ##print "**IdbProxy.call %s %s %s" % (methodname, args, kwargs) value = self.conn.remotecall(self.oid, methodname, args, kwargs) - ##print "**IdbProxy.call %s returns %s" % (methodname, `value`) + ##print "**IdbProxy.call %s returns %r" % (methodname, value) return value def run(self, cmd, locals): diff --git a/Lib/idlelib/ScriptBinding.py b/Lib/idlelib/ScriptBinding.py index c0fa88f..a1d937b 100644 --- a/Lib/idlelib/ScriptBinding.py +++ b/Lib/idlelib/ScriptBinding.py @@ -145,16 +145,16 @@ class ScriptBinding: dirname = os.path.dirname(filename) # XXX Too often this discards arguments the user just set... interp.runcommand("""if 1: - _filename = %s + _filename = %r import sys as _sys from os.path import basename as _basename if (not _sys.argv or _basename(_sys.argv[0]) != _basename(_filename)): _sys.argv = [_filename] import os as _os - _os.chdir(%s) + _os.chdir(%r) del _filename, _sys, _basename, _os - \n""" % (`filename`, `dirname`)) + \n""" % (filename, dirname)) interp.prepend_syspath(filename) interp.runcode(code) diff --git a/Lib/idlelib/TreeWidget.py b/Lib/idlelib/TreeWidget.py index 824bdca..1c9eb2e 100644 --- a/Lib/idlelib/TreeWidget.py +++ b/Lib/idlelib/TreeWidget.py @@ -31,7 +31,7 @@ except NameError: if os.path.isdir(_icondir): ICONDIR = _icondir elif not os.path.isdir(ICONDIR): - raise RuntimeError, "can't find icon directory (%s)" % `ICONDIR` + raise RuntimeError, "can't find icon directory (%r)" % (ICONDIR,) def listicons(icondir=ICONDIR): """Utility to display the available icons.""" diff --git a/Lib/idlelib/UndoDelegator.py b/Lib/idlelib/UndoDelegator.py index 2452a98..182a117 100644 --- a/Lib/idlelib/UndoDelegator.py +++ b/Lib/idlelib/UndoDelegator.py @@ -177,7 +177,7 @@ class Command: t = (self.index1, self.index2, self.chars, self.tags) if self.tags is None: t = t[:-1] - return s + `t` + return s + repr(t) def do(self, text): pass @@ -310,7 +310,7 @@ class CommandSequence(Command): s = self.__class__.__name__ strs = [] for cmd in self.cmds: - strs.append(" " + `cmd`) + strs.append(" %r" % (cmd,)) return s + "(\n" + ",\n".join(strs) + "\n)" def __len__(self): diff --git a/Lib/idlelib/WidgetRedirector.py b/Lib/idlelib/WidgetRedirector.py index be74668f..df60cea 100644 --- a/Lib/idlelib/WidgetRedirector.py +++ b/Lib/idlelib/WidgetRedirector.py @@ -69,7 +69,7 @@ class OriginalCommand: self.orig_and_name = (self.orig, self.name) def __repr__(self): - return "OriginalCommand(%s, %s)" % (`self.redir`, `self.name`) + return "OriginalCommand(%r, %r)" % (self.redir, self.name) def __call__(self, *args): return self.tk_call(self.orig_and_name + args) diff --git a/Lib/idlelib/aboutDialog.py b/Lib/idlelib/aboutDialog.py index 3d2bcf6..c121061 100644 --- a/Lib/idlelib/aboutDialog.py +++ b/Lib/idlelib/aboutDialog.py @@ -66,7 +66,7 @@ class AboutDialog(Toplevel): sys.version.split()[0], fg=self.fg, bg=self.bg) labelPythonVer.grid(row=9, column=0, sticky=W, padx=10, pady=0) # handle weird tk version num in windoze python >= 1.6 (?!?) - tkVer = `TkVersion`.split('.') + tkVer = repr(TkVersion).split('.') tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:] if tkVer[len(tkVer)-1] == '': tkVer[len(tkVer)-1] = '0' @@ -141,8 +141,7 @@ class AboutDialog(Toplevel): except IOError: import tkMessageBox tkMessageBox.showerror(title='File Load Error', - message='Unable to load file '+ - `fn`+' .', + message='Unable to load file %r .' % (fn,), parent=self) return else: diff --git a/Lib/idlelib/configDialog.py b/Lib/idlelib/configDialog.py index 8c3eb3e..4e4e564 100644 --- a/Lib/idlelib/configDialog.py +++ b/Lib/idlelib/configDialog.py @@ -718,7 +718,7 @@ class ConfigDialog(Toplevel): def DeleteCustomKeys(self): keySetName=self.customKeys.get() if not tkMessageBox.askyesno('Delete Key Set','Are you sure you wish '+ - 'to delete the key set '+`keySetName`+' ?', + 'to delete the key set %r ?' % (keySetName), parent=self): return #remove key set from config @@ -745,7 +745,7 @@ class ConfigDialog(Toplevel): def DeleteCustomTheme(self): themeName=self.customTheme.get() if not tkMessageBox.askyesno('Delete Theme','Are you sure you wish '+ - 'to delete the theme '+`themeName`+' ?', + 'to delete the theme %r ?' % (themeName,), parent=self): return #remove theme from config diff --git a/Lib/idlelib/configHandler.py b/Lib/idlelib/configHandler.py index 3d79fb9..d1c2b3c 100644 --- a/Lib/idlelib/configHandler.py +++ b/Lib/idlelib/configHandler.py @@ -231,10 +231,11 @@ class IdleConf: elif self.defaultCfg[configType].has_option(section,option): return self.defaultCfg[configType].Get(section, option, type=type) else: #returning default, print warning - warning=('\n Warning: configHandler.py - IdleConf.GetOption -\n'+ - ' problem retrieving configration option '+`option`+'\n'+ - ' from section '+`section`+'.\n'+ - ' returning default value: '+`default`+'\n') + warning=('\n Warning: configHandler.py - IdleConf.GetOption -\n' + ' problem retrieving configration option %r\n' + ' from section %r.\n' + ' returning default value: %r\n' % + (option, section, default)) sys.stderr.write(warning) return default @@ -331,10 +332,11 @@ class IdleConf: for element in theme.keys(): if not cfgParser.has_option(themeName,element): #we are going to return a default, print warning - warning=('\n Warning: configHandler.py - IdleConf.GetThemeDict'+ - ' -\n problem retrieving theme element '+`element`+ - '\n from theme '+`themeName`+'.\n'+ - ' returning default value: '+`theme[element]`+'\n') + warning=('\n Warning: configHandler.py - IdleConf.GetThemeDict' + ' -\n problem retrieving theme element %r' + '\n from theme %r.\n' + ' returning default value: %r\n' % + (element, themeName, theme[element])) sys.stderr.write(warning) colour=cfgParser.Get(themeName,element,default=theme[element]) theme[element]=colour @@ -561,10 +563,11 @@ class IdleConf: if binding: keyBindings[event]=binding else: #we are going to return a default, print warning - warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'+ - ' -\n problem retrieving key binding for event '+ - `event`+'\n from key set '+`keySetName`+'.\n'+ - ' returning default value: '+`keyBindings[event]`+'\n') + warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys' + ' -\n problem retrieving key binding for event %r' + '\n from key set %r.\n' + ' returning default value: %r\n' % + (event, keySetName, keyBindings[event])) sys.stderr.write(warning) return keyBindings diff --git a/Lib/idlelib/rpc.py b/Lib/idlelib/rpc.py index d3a9fd8..d097f9b 100644 --- a/Lib/idlelib/rpc.py +++ b/Lib/idlelib/rpc.py @@ -58,7 +58,7 @@ def pickle_code(co): # def pickle_function(fn): # assert isinstance(fn, type.FunctionType) -# return `fn` +# return repr(fn) copy_reg.pickle(types.CodeType, pickle_code, unpickle_code) # copy_reg.pickle(types.FunctionType, pickle_function, unpickle_function) @@ -170,7 +170,7 @@ class SocketIO: except TypeError: return ("ERROR", "Bad request format") if not self.objtable.has_key(oid): - return ("ERROR", "Unknown object id: %s" % `oid`) + return ("ERROR", "Unknown object id: %r" % (oid,)) obj = self.objtable[oid] if methodname == "__methods__": methods = {} @@ -181,7 +181,7 @@ class SocketIO: _getattributes(obj, attributes) return ("OK", attributes) if not hasattr(obj, methodname): - return ("ERROR", "Unsupported method name: %s" % `methodname`) + return ("ERROR", "Unsupported method name: %r" % (methodname,)) method = getattr(obj, methodname) try: if how == 'CALL': @@ -321,7 +321,7 @@ class SocketIO: try: s = pickle.dumps(message) except pickle.PicklingError: - print >>sys.__stderr__, "Cannot pickle:", `message` + print >>sys.__stderr__, "Cannot pickle:", repr(message) raise s = struct.pack(" 0: @@ -377,7 +377,7 @@ class SocketIO: message = pickle.loads(packet) except pickle.UnpicklingError: print >>sys.__stderr__, "-----------------------" - print >>sys.__stderr__, "cannot unpickle packet:", `packet` + print >>sys.__stderr__, "cannot unpickle packet:", repr(packet) traceback.print_stack(file=sys.__stderr__) print >>sys.__stderr__, "-----------------------" raise diff --git a/Lib/idlelib/textView.py b/Lib/idlelib/textView.py index be3ade0..917a6cc 100644 --- a/Lib/idlelib/textView.py +++ b/Lib/idlelib/textView.py @@ -46,7 +46,7 @@ class TextViewer(Toplevel): textFile = open(fileName, 'r') except IOError: tkMessageBox.showerror(title='File Load Error', - message='Unable to load file '+`fileName`+' .') + message='Unable to load file %r .' % (fileName,)) else: self.textView.insert(0.0,textFile.read()) diff --git a/Lib/ihooks.py b/Lib/ihooks.py index 19faac9..936a950 100644 --- a/Lib/ihooks.py +++ b/Lib/ihooks.py @@ -273,8 +273,8 @@ class ModuleLoader(BasicModuleLoader): elif type == PKG_DIRECTORY: m = self.hooks.load_package(name, filename, file) else: - raise ImportError, "Unrecognized module type (%s) for %s" % \ - (`type`, name) + raise ImportError, "Unrecognized module type (%r) for %s" % \ + (type, name) finally: if file: file.close() m.__file__ = filename @@ -299,8 +299,8 @@ class FancyModuleLoader(ModuleLoader): if inittype not in (PY_COMPILED, PY_SOURCE): if initfile: initfile.close() raise ImportError, \ - "Bad type (%s) for __init__ module in package %s" % ( - `inittype`, name) + "Bad type (%r) for __init__ module in package %s" % ( + inittype, name) path = [filename] file = initfile realfilename = initfilename diff --git a/Lib/imaplib.py b/Lib/imaplib.py index 8004982..0112ddc 100644 --- a/Lib/imaplib.py +++ b/Lib/imaplib.py @@ -192,7 +192,7 @@ class IMAP4: if __debug__: if self.debug >= 3: - self._mesg('CAPABILITIES: %s' % `self.capabilities`) + self._mesg('CAPABILITIES: %r' % (self.capabilities,)) for version in AllowedVersions: if not version in self.capabilities: @@ -972,7 +972,7 @@ class IMAP4: self.mo = cre.match(s) if __debug__: if self.mo is not None and self.debug >= 5: - self._mesg("\tmatched r'%s' => %s" % (cre.pattern, `self.mo.groups()`)) + self._mesg("\tmatched r'%s' => %r" % (cre.pattern, self.mo.groups())) return self.mo is not None @@ -1416,7 +1416,7 @@ if __name__ == '__main__': if M.state == 'AUTH': test_seq1 = test_seq1[1:] # Login not needed M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION) - M._mesg('CAPABILITIES = %s' % `M.capabilities`) + M._mesg('CAPABILITIES = %r' % (M.capabilities,)) for cmd,args in test_seq1: run(cmd, args) diff --git a/Lib/lib-tk/FileDialog.py b/Lib/lib-tk/FileDialog.py index 323dc29..5e848da 100644 --- a/Lib/lib-tk/FileDialog.py +++ b/Lib/lib-tk/FileDialog.py @@ -244,7 +244,7 @@ class SaveFileDialog(FileDialog): return d = Dialog(self.top, title="Overwrite Existing File Question", - text="Overwrite existing file %s?" % `file`, + text="Overwrite existing file %r?" % (file,), bitmap='questhead', default=1, strings=("Yes", "Cancel")) diff --git a/Lib/lib-tk/Tix.py b/Lib/lib-tk/Tix.py index 99731cd..9114538 100755 --- a/Lib/lib-tk/Tix.py +++ b/Lib/lib-tk/Tix.py @@ -374,9 +374,9 @@ class TixWidget(Tkinter.Widget): if option == '': return elif not isinstance(option, StringType): - option = `option` + option = repr(option) if not isinstance(value, StringType): - value = `value` + value = repr(value) names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, value) diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py index b5b0af3..67e942e 100644 --- a/Lib/lib-tk/Tkinter.py +++ b/Lib/lib-tk/Tkinter.py @@ -177,7 +177,7 @@ class Variable: master = _default_root self._master = master self._tk = master.tk - self._name = 'PY_VAR' + `_varnum` + self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._default) def __del__(self): @@ -1022,7 +1022,7 @@ class Misc: be executed. An optional function SUBST can be given which will be executed before FUNC.""" f = CallWrapper(func, subst, self).__call__ - name = `id(f)` + name = repr(id(f)) try: func = func.im_func except AttributeError: @@ -1810,7 +1810,7 @@ class BaseWidget(Misc): name = cnf['name'] del cnf['name'] if not name: - name = `id(self)` + name = repr(id(self)) self._name = name if master._w=='.': self._w = '.' + name @@ -1957,9 +1957,9 @@ def AtSelLast(): return 'sel.last' def At(x, y=None): if y is None: - return '@' + `x` + return '@%r' % (x,) else: - return '@' + `x` + ',' + `y` + return '@%r,%r' % (x, y) class Canvas(Widget): """Canvas widget to display graphical elements like lines or text.""" @@ -3118,7 +3118,7 @@ class Image: self.tk = master.tk if not name: Image._last_id += 1 - name = "pyimage" +`Image._last_id` # tk itself would use image + name = "pyimage%r" % (Image._last_id,) # tk itself would use image # The following is needed for systems where id(x) # can return a negative number, such as Linux/m68k: if name[0] == '-': name = '_' + name[1:] diff --git a/Lib/lib-tk/turtle.py b/Lib/lib-tk/turtle.py index b56d91c..a395613 100644 --- a/Lib/lib-tk/turtle.py +++ b/Lib/lib-tk/turtle.py @@ -95,18 +95,18 @@ class RawPen: try: id = self._canvas.create_line(0, 0, 0, 0, fill=color) except Tkinter.TclError: - raise Error, "bad color string: %s" % `color` + raise Error, "bad color string: %r" % (color,) self._set_color(color) return try: r, g, b = color except: - raise Error, "bad color sequence: %s" % `color` + raise Error, "bad color sequence: %r" % (color,) else: try: r, g, b = args except: - raise Error, "bad color arguments: %s" % `args` + raise Error, "bad color arguments: %r" % (args,) assert 0 <= r <= 1 assert 0 <= g <= 1 assert 0 <= b <= 1 @@ -240,12 +240,12 @@ class RawPen: try: x, y = args[0] except: - raise Error, "bad point argument: %s" % `args[0]` + raise Error, "bad point argument: %r" % (args[0],) else: try: x, y = args except: - raise Error, "bad coordinates: %s" % `args[0]` + raise Error, "bad coordinates: %r" % (args[0],) x0, y0 = self._origin self._goto(x0+x, y0-y) diff --git a/Lib/macurl2path.py b/Lib/macurl2path.py index 3c1acc0..ed23883 100644 --- a/Lib/macurl2path.py +++ b/Lib/macurl2path.py @@ -80,7 +80,7 @@ def test(): "/foo/bar/index.html", "/foo/bar/", "/"]: - print `url`, '->', `url2pathname(url)` + print '%r -> %r' % (url, url2pathname(url)) for path in ["drive:", "drive:dir:", "drive:dir:file", @@ -89,7 +89,7 @@ def test(): ":file", ":dir:", ":dir:file"]: - print `path`, '->', `pathname2url(path)` + print '%r -> %r' % (path, pathname2url(path)) if __name__ == '__main__': test() diff --git a/Lib/markupbase.py b/Lib/markupbase.py index 62587e0..c1e5acd 100644 --- a/Lib/markupbase.py +++ b/Lib/markupbase.py @@ -124,7 +124,7 @@ class ParserBase: self.error("unexpected '[' char in declaration") else: self.error( - "unexpected %s char in declaration" % `rawdata[j]`) + "unexpected %r char in declaration" % rawdata[j]) if j < 0: return j return -1 # incomplete @@ -144,7 +144,7 @@ class ParserBase: # look for MS Office ]> ending match= _msmarkedsectionclose.search(rawdata, i+3) else: - self.error('unknown status keyword %s in marked section' % `rawdata[i+3:j]`) + self.error('unknown status keyword %r in marked section' % rawdata[i+3:j]) if not match: return -1 if report: @@ -180,8 +180,7 @@ class ParserBase: return -1 if s != "/dev/null" % `seq`).read() + stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read() list = map(int, stuff.split()) print list, "<-- pick" do('f.listmessages()') diff --git a/Lib/mimetools.py b/Lib/mimetools.py index 067a2cd..0b698ac 100644 --- a/Lib/mimetools.py +++ b/Lib/mimetools.py @@ -129,11 +129,11 @@ def choose_boundary(): import socket hostid = socket.gethostbyname(socket.gethostname()) try: - uid = `os.getuid()` + uid = repr(os.getuid()) except AttributeError: uid = '1' try: - pid = `os.getpid()` + pid = repr(os.getpid()) except AttributeError: pid = '1' _prefix = hostid + '.' + uid + '.' + pid diff --git a/Lib/modulefinder.py b/Lib/modulefinder.py index 6dec0e5..07b260d 100644 --- a/Lib/modulefinder.py +++ b/Lib/modulefinder.py @@ -62,11 +62,11 @@ class Module: self.starimports = {} def __repr__(self): - s = "Module(%s" % `self.__name__` + s = "Module(%r" % % (self.__name__,) if self.__file__ is not None: - s = s + ", %s" % `self.__file__` + s = s + ", %r" % (self.__file__,) if self.__path__ is not None: - s = s + ", %s" % `self.__path__` + s = s + ", %r" % (self.__path__,) s = s + ")" return s @@ -564,7 +564,7 @@ def test(): if debug > 1: print "path:" for item in path: - print " ", `item` + print " ", repr(item) # Create the module finder and turn its crank mf = ModuleFinder(path, debug, exclude) diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 6299ba2..83544b8 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -175,7 +175,7 @@ class NNTP: If the response code is 200, posting is allowed; if it 201, posting is not allowed.""" - if self.debugging: print '*welcome*', `self.welcome` + if self.debugging: print '*welcome*', repr(self.welcome) return self.welcome def set_debuglevel(self, level): @@ -190,12 +190,12 @@ class NNTP: def putline(self, line): """Internal: send one line to the server, appending CRLF.""" line = line + CRLF - if self.debugging > 1: print '*put*', `line` + if self.debugging > 1: print '*put*', repr(line) self.sock.sendall(line) def putcmd(self, line): """Internal: send one command to the server (through putline()).""" - if self.debugging: print '*cmd*', `line` + if self.debugging: print '*cmd*', repr(line) self.putline(line) def getline(self): @@ -203,7 +203,7 @@ class NNTP: Raise EOFError if the connection is closed.""" line = self.file.readline() if self.debugging > 1: - print '*get*', `line` + print '*get*', repr(line) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] @@ -213,7 +213,7 @@ class NNTP: """Internal: get a response from the server. Raise various errors if the response indicates an error.""" resp = self.getline() - if self.debugging: print '*resp*', `resp` + if self.debugging: print '*resp*', repr(resp) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) diff --git a/Lib/opcode.py b/Lib/opcode.py index cfde5f8..39d4bd2 100644 --- a/Lib/opcode.py +++ b/Lib/opcode.py @@ -21,7 +21,7 @@ hasfree = [] opmap = {} opname = [''] * 256 -for op in range(256): opname[op] = '<' + `op` + '>' +for op in range(256): opname[op] = '<%r>' % (op,) del op def def_op(name, op): diff --git a/Lib/pdb.py b/Lib/pdb.py index 9a08a6a..b35164c 100755 --- a/Lib/pdb.py +++ b/Lib/pdb.py @@ -219,7 +219,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): filename = arg[:colon].rstrip() f = self.lookupmodule(filename) if not f: - print '*** ', `filename`, + print '*** ', repr(filename), print 'not found from sys.path' return else: @@ -252,7 +252,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): (ok, filename, ln) = self.lineinfo(arg) if not ok: print '*** The specified object', - print `arg`, + print repr(arg), print 'is not a function' print ('or was not found ' 'along sys.path.') @@ -596,7 +596,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): if isinstance(t, str): exc_type_name = t else: exc_type_name = t.__name__ - print '***', exc_type_name + ':', `v` + print '***', exc_type_name + ':', repr(v) raise def do_p(self, arg): @@ -627,7 +627,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): else: first = max(1, int(x) - 5) except: - print '*** Error in argument:', `arg` + print '*** Error in argument:', repr(arg) return elif self.lineno is None: first = max(1, self.curframe.f_lineno - 5) @@ -644,7 +644,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): print '[EOF]' break else: - s = `lineno`.rjust(3) + s = repr(lineno).rjust(3) if len(s) < 4: s = s + ' ' if lineno in breaklist: s = s + 'B' else: s = s + ' ' @@ -665,7 +665,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ - print '***', exc_type_name + ':', `v` + print '***', exc_type_name + ':', repr(v) return code = None # Is it a function? @@ -1034,7 +1034,7 @@ if __name__=='__main__': mainpyfile = filename = sys.argv[1] # Get script filename if not os.path.exists(filename): - print 'Error:', `filename`, 'does not exist' + print 'Error:', repr(filename), 'does not exist' sys.exit(1) mainmodule = os.path.basename(filename) del sys.argv[0] # Hide "pdb.py" from argument list @@ -1042,4 +1042,4 @@ if __name__=='__main__': # Insert script directory in front of module search path sys.path.insert(0, os.path.dirname(filename)) - run('execfile(' + `filename` + ')') + run('execfile(%r)' % (filename,)) diff --git a/Lib/pickle.py b/Lib/pickle.py index a854948..69fc2cc 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -261,7 +261,7 @@ class Pickler: else: return LONG_BINPUT + pack("d', obj)) else: - self.write(FLOAT + `obj` + '\n') + self.write(FLOAT + repr(obj) + '\n') dispatch[FloatType] = save_float def save_string(self, obj, pack=struct.pack): @@ -499,7 +499,7 @@ class Pickler: else: self.write(BINSTRING + pack("' + """t.__repr__() implements repr(t).""" + return '