Permalink
Browse files

Merge classical-division-5689: Remove uses of classical division

Author: vperic
Reviewer: itamar
Fixes: #5689

The "classical" division operator "/" has been deprecated for a long while
(Python 2.2 I believe) as it is ambiguous - it means floor division with ints,
but true division otherwise. In Python 3, the "/" operator is for true
division (always returns a float), while the unambiguous operator "//" should
be used for floor division. As such, it is required to explicitly either
import division from __future__ or use the floor division operator.

Most of the time, division was used to force a ZeroDivisionError, for
testing purposes. In such cases, I've usually imported from __future__,
though in some cases I just changed the line to use the floor operator. These
changes are still important, as they will hide the warnings produced by
"-3" and make it easier to spot the real errors (of which there were about
twenty).

git-svn-id: svn://svn.twistedmatrix.com/svn/Twisted/trunk@34523 bbbe8e31-12d6-0310-92fd-ac37d47ddeeb
  • Loading branch information...
vperic
vperic committed Jun 7, 2012
1 parent 7ae6c01 commit 9aa13ffa5e739985e603c922fa1b0ea70672c592
@@ -235,7 +235,7 @@ def ssh_CHANNEL_DATA(self, packet):
#packet = packet[:channel.localWindowLeft+4]
data = common.getNS(packet[4:])[0]
channel.localWindowLeft -= dataLength
- if channel.localWindowLeft < channel.localWindowSize / 2:
+ if channel.localWindowLeft < channel.localWindowSize // 2:
self.adjustWindow(channel, channel.localWindowSize - \
channel.localWindowLeft)
#log.msg('local window left: %s/%s' % (channel.localWindowLeft,
@@ -264,7 +264,7 @@ def ssh_CHANNEL_EXTENDED_DATA(self, packet):
return
data = common.getNS(packet[8:])[0]
channel.localWindowLeft -= dataLength
- if channel.localWindowLeft < channel.localWindowSize / 2:
+ if channel.localWindowLeft < channel.localWindowSize // 2:
self.adjustWindow(channel, channel.localWindowSize -
channel.localWindowLeft)
log.callWithLogger(channel, channel.extReceived, typeCode, data)
@@ -22,7 +22,7 @@ def determineDefaultFunctionName():
compiled from interactive input or at the top-level of modules.
"""
try:
- 1 / 0
+ 1 // 0
except:
# The last frame is this function. The second to last frame is this
# function's caller, which is module-scope, which is what we want,
@@ -188,7 +188,7 @@ def test_connectionLostFailed(self):
"""
port = Port(12345, ServerFactory())
port.connected = True
- port.connectionLost = lambda reason: 1 / 0
+ port.connectionLost = lambda reason: 1 // 0
return self.assertFailure(port.stopListening(), ZeroDivisionError)
View
@@ -1919,7 +1919,7 @@ def spew_internaldate(self, id, msg, _w=None, _f=None):
sign = "+"
else:
sign = "-"
- odate = odate + sign + str(((abs(ttup[9]) / 3600) * 100 + (abs(ttup[9]) % 3600) / 60)).zfill(4)
+ odate = odate + sign + str(((abs(ttup[9]) // 3600) * 100 + (abs(ttup[9]) % 3600) // 60)).zfill(4)
_w('INTERNALDATE ' + _quote(odate))
def spew_rfc822header(self, id, msg, _w=None, _f=None):
View
@@ -289,7 +289,7 @@ def rfc822date(timeinfo=None,local=1):
(tzhr, tzmin) = divmod(abs(tz), 3600)
if tz:
- tzhr *= int(abs(tz)/tz)
+ tzhr *= int(abs(tz)//tz)
(tzmin, tzsec) = divmod(tzmin, 60)
else:
(tzhr, tzmin) = (0,0)
@@ -476,7 +476,7 @@ def test_chdir(self):
def chAndBreak():
os.mkdir('releaseCh')
os.chdir('releaseCh')
- 1/0
+ 1//0
self.assertRaises(ZeroDivisionError,
release.runChdirSafe, chAndBreak)
self.assertEqual(cwd, os.getcwd())
@@ -4,6 +4,7 @@
"""
Python 2.5+ test cases for failures thrown into generators.
"""
+from __future__ import division
import sys
import traceback
@@ -1,4 +1,4 @@
# Helper module for a test_reflect test
-1/0
+1//0
View
@@ -655,7 +655,7 @@ def test_callRemoteSuccessLocalCallbackErrorLogging(self):
self.sender.expectError()
callResult = self.dispatcher.callRemote(Hello, hello='world')
- callResult.addCallback(lambda result: 1 / 0)
+ callResult.addCallback(lambda result: 1 // 0)
self.dispatcher.ampBoxReceived(amp.AmpBox({
'hello': "yay", 'print': "ignored", '_answer': "1"}))
@@ -671,7 +671,7 @@ def test_callRemoteErrorLocalCallbackErrorLogging(self):
self.sender.expectError()
callResult = self.dispatcher.callRemote(Hello, hello='world')
- callResult.addErrback(lambda result: 1 / 0)
+ callResult.addErrback(lambda result: 1 // 0)
self.dispatcher.ampBoxReceived(amp.AmpBox({
'_error': '1', '_error_code': 'bugs',
@@ -476,7 +476,7 @@ def testPickledTimer(self):
def testBrokenTimer(self):
d = defer.Deferred()
- t = internet.TimerService(1, lambda: 1 / 0)
+ t = internet.TimerService(1, lambda: 1 // 0)
oldFailed = t._failed
def _failed(why):
oldFailed(why)
@@ -111,7 +111,7 @@ def test_decodeTooLargeLong(self):
self.enc.sendEncoded(smallest)
encoded = self.io.getvalue()
self.io.truncate(0)
- self.enc.setPrefixLimit(self.enc.prefixLimit / 2)
+ self.enc.setPrefixLimit(self.enc.prefixLimit // 2)
self.assertRaises(banana.BananaError, self.enc.dataReceived, encoded)
@@ -139,7 +139,7 @@ def test_decodeTooSmallLong(self):
self.enc.sendEncoded(largest)
encoded = self.io.getvalue()
self.io.truncate(0)
- self.enc.setPrefixLimit(self.enc.prefixLimit / 2)
+ self.enc.setPrefixLimit(self.enc.prefixLimit // 2)
self.assertRaises(banana.BananaError, self.enc.dataReceived, encoded)
View
@@ -240,7 +240,7 @@ def testPausedFailure(self):
def testCallbackErrors(self):
l = []
- d = defer.Deferred().addCallback(lambda _: 1 / 0).addErrback(l.append)
+ d = defer.Deferred().addCallback(lambda _: 1 // 0).addErrback(l.append)
d.callback(1)
self.assert_(isinstance(l[0].value, ZeroDivisionError))
l = []
@@ -1098,7 +1098,7 @@ def test_comparison(self):
compare equal to instances of other types.
"""
try:
- 1 / 0
+ 1 // 0
except:
firstFailure = failure.Failure()
@@ -1565,7 +1565,7 @@ def test_errorLog(self):
and its final result (the one not handled by any callback) is an
exception, that exception will be logged immediately.
"""
- defer.Deferred().addCallback(lambda x: 1 / 0).callback(1)
+ defer.Deferred().addCallback(lambda x: 1 // 0).callback(1)
gc.collect()
self._check()
@@ -1575,7 +1575,7 @@ def test_errorLogWithInnerFrameRef(self):
"""
def _subErrorLogWithInnerFrameRef():
d = defer.Deferred()
- d.addCallback(lambda x: 1 / 0)
+ d.addCallback(lambda x: 1 // 0)
d.callback(1)
_subErrorLogWithInnerFrameRef()
@@ -1588,7 +1588,7 @@ def test_errorLogWithInnerFrameCycle(self):
"""
def _subErrorLogWithInnerFrameCycle():
d = defer.Deferred()
- d.addCallback(lambda x, d=d: 1 / 0)
+ d.addCallback(lambda x, d=d: 1 // 0)
d._d = d
d.callback(1)
@@ -120,7 +120,7 @@ def _genBasics(self):
def _genBuggy(self):
yield waitForDeferred(getThing())
- 1/0
+ 1//0
_genBuggy = deferredGenerator(_genBuggy)
@@ -4,6 +4,7 @@
"""
Test cases for failure module.
"""
+from __future__ import division
import re
import sys
View
@@ -83,7 +83,7 @@ def test_erroneousErrors(self):
L1 = []
L2 = []
def broken(events):
- 1 / 0
+ 1 // 0
for observer in [L1.append, broken, L2.append]:
log.addObserver(observer)
@@ -258,13 +258,13 @@ def flush(self):
class EvilStr:
def __str__(self):
- 1/0
+ 1//0
class EvilRepr:
def __str__(self):
return "Happy Evil Repr"
def __repr__(self):
- 1/0
+ 1//0
class EvilReprStr(EvilStr, EvilRepr):
pass
@@ -232,7 +232,7 @@ def testBuffer(self):
t = proto_helpers.StringIOWithoutClosing()
a = LineTester()
a.makeConnection(protocol.FileWrapper(t))
- for i in range(len(self.buffer)/packet_size + 1):
+ for i in range(len(self.buffer) // packet_size + 1):
s = self.buffer[i*packet_size:(i+1)*packet_size]
a.dataReceived(s)
self.assertEqual(self.output, a.received)
@@ -254,7 +254,7 @@ def test_pausing(self):
clock = task.Clock()
a = LineTester(clock)
a.makeConnection(protocol.FileWrapper(t))
- for i in range(len(self.pause_buf)/packet_size + 1):
+ for i in range(len(self.pause_buf) // packet_size + 1):
s = self.pause_buf[i*packet_size:(i+1)*packet_size]
a.dataReceived(s)
self.assertEqual(self.pause_output1, a.received)
@@ -277,7 +277,7 @@ def test_rawPausing(self):
clock = task.Clock()
a = LineTester(clock)
a.makeConnection(protocol.FileWrapper(t))
- for i in range(len(self.rawpause_buf)/packet_size + 1):
+ for i in range(len(self.rawpause_buf) // packet_size + 1):
s = self.rawpause_buf[i*packet_size:(i+1)*packet_size]
a.dataReceived(s)
self.assertEqual(self.rawpause_output1, a.received)
@@ -297,7 +297,7 @@ def test_stopProducing(self):
t = proto_helpers.StringIOWithoutClosing()
a = LineTester()
a.makeConnection(protocol.FileWrapper(t))
- for i in range(len(self.stop_buf)/packet_size + 1):
+ for i in range(len(self.stop_buf) // packet_size + 1):
s = self.stop_buf[i*packet_size:(i+1)*packet_size]
a.dataReceived(s)
self.assertEqual(self.stop_output, a.received)
@@ -455,7 +455,7 @@ def test_buffer(self):
for s in self.strings:
a.sendString(s)
out = t.value()
- for i in range(len(out)/packet_size + 1):
+ for i in range(len(out) // packet_size + 1):
s = out[i*packet_size:(i+1)*packet_size]
if s:
a.dataReceived(s)
@@ -275,7 +275,7 @@ def test_deferredFailureAfterSuccess(self):
# alas, this test appears to flunk the default reactor too
d = threads.deferToThread(lambda: None)
- d.addCallback(lambda ign: threads.deferToThread(lambda: 1/0))
+ d.addCallback(lambda ign: threads.deferToThread(lambda: 1//0))
return self.assertFailure(d, ZeroDivisionError)
No changes.
@@ -1,6 +1,7 @@
# -*- test-case-name: twisted.trial.test.test_tests -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+from __future__ import division
from twisted.trial import unittest, util
from twisted.internet import reactor, protocol, defer
@@ -3,7 +3,7 @@
# this module is a trivial class with doctests and a __test__ attribute
# to test trial's doctest support with python2.4
-
+from __future__ import division
class Counter(object):
"""a simple counter object for testing trial's doctest support
@@ -4,6 +4,7 @@
"""
Tests for assertions provided by L{twisted.trial.unittest.TestCase}.
"""
+from __future__ import division
import warnings
from pprint import pformat
@@ -4,6 +4,7 @@
"""
Test the interaction between trial and errors logged during test run.
"""
+from __future__ import division
import time
@@ -2,7 +2,7 @@
# See LICENSE for details.
#
# Maintainer: Jonathan Lange
-
+from __future__ import division
import sys
import traceback
@@ -6,7 +6,7 @@
"""
Tests for L{twisted.trial.reporter}.
"""
-
+from __future__ import division
import errno, sys, os, re, StringIO
from inspect import getmro
@@ -1,3 +1,5 @@
+from __future__ import division
+
from twisted.trial import unittest
from twisted.internet import defer
View
@@ -5,6 +5,7 @@
"""
Static resources for L{twisted.web}.
"""
+from __future__ import division
import os
import warnings
@@ -656,7 +656,7 @@ class FailingElement(Element):
def render(self, request):
a = 42
b = 0
- return a / b
+ return a // b
@@ -1215,7 +1215,7 @@ def test_startProducing(self):
producer = FileBodyProducer(
StringIO(expectedResult), self.cooperator, readSize)
complete = producer.startProducing(consumer)
- for i in range(len(expectedResult) / readSize + 1):
+ for i in range(len(expectedResult) // readSize + 1):
self._scheduled.pop(0)()
self.assertEqual([], self._scheduled)
self.assertEqual(expectedResult, output.getvalue())
@@ -1233,7 +1233,7 @@ def test_inputClosedAtEOF(self):
producer = FileBodyProducer(inputFile, self.cooperator, readSize)
consumer = FileConsumer(StringIO())
producer.startProducing(consumer)
- for i in range(len(inputBytes) / readSize + 2):
+ for i in range(len(inputBytes) // readSize + 2):
self._scheduled.pop(0)()
self.assertTrue(inputFile.closed)
@@ -543,7 +543,7 @@ def testUnicodeTolerance(self):
'\x80\x95\xb6[\xea0\xb90\xc80 \x00<\x00/\x00T\x00I\x00T\x00L\x00E'
'\x00>\x00<\x00/\x00J\x00A\x00P\x00A\x00N\x00E\x00S\x00E\x00>\x00')
def reverseBytes(s):
- fmt = str(len(s) / 2) + 'H'
+ fmt = str(len(s) // 2) + 'H'
return struct.pack('<' + fmt, *struct.unpack('>' + fmt, s))
urd = microdom.parseString(reverseBytes(s.encode('UTF-16')))
ud = microdom.parseString(s.encode('UTF-16'))
View
@@ -254,7 +254,7 @@ def outReceived(self, output):
headerend, delimiter = headerEnds[0]
self.headertext = text[:headerend]
# This is a final version of the header text.
- linebreak = delimiter[:len(delimiter)/2]
+ linebreak = delimiter[:len(delimiter)//2]
headers = self.headertext.split(linebreak)
for header in headers:
br = header.find(': ')
@@ -1576,7 +1576,7 @@ def test_splitLongMessagesWithOverride(self):
"""
message = 'o' * (irc.MAX_COMMAND_LENGTH - 2)
self.assertLongMessageSplitting(
- message, 3, length=irc.MAX_COMMAND_LENGTH / 2)
+ message, 3, length=irc.MAX_COMMAND_LENGTH // 2)
def test_newlinesBeforeLineBreaking(self):

0 comments on commit 9aa13ff

Please sign in to comment.