Use python3 range.

Including potential memory reduction due to not created unnecessary lists.
This commit is contained in:
Ahmed Charles 2015-11-02 11:47:07 +00:00
parent ee0db7a50d
commit bcd8674ef3
20 changed files with 66 additions and 46 deletions

View file

@ -4,6 +4,7 @@ The base Command class.
All commands in Evennia inherit from the 'Command' class in this module. All commands in Evennia inherit from the 'Command' class in this module.
""" """
from builtins import range
import re import re
from evennia.locks.lockhandler import LockHandler from evennia.locks.lockhandler import LockHandler

View file

@ -17,6 +17,8 @@ the Evennia API. It is also a severe security risk and should
therefore always be limited to superusers only. therefore always be limited to superusers only.
""" """
from builtins import range
from traceback import format_exc from traceback import format_exc
from django.conf import settings from django.conf import settings
from evennia.utils.batchprocessors import BATCHCMD, BATCHCODE from evennia.utils.batchprocessors import BATCHCMD, BATCHCODE

View file

@ -4,6 +4,8 @@ import sys
Building and world design commands Building and world design commands
""" """
from builtins import range
import re import re
from django.conf import settings from django.conf import settings
from django.db.models import Q from django.db.models import Q

View file

@ -19,6 +19,8 @@ self.msg() and similar methods to reroute returns to the correct
method. Otherwise all text will be returned to all connected sessions. method. Otherwise all text will be returned to all connected sessions.
""" """
from builtins import range
import time import time
from django.conf import settings from django.conf import settings
from evennia.server.sessionhandler import SESSIONS from evennia.server.sessionhandler import SESSIONS

View file

@ -29,6 +29,7 @@ at_cmdset_creation():
After a reload the dice (or roll) command will be available in-game. After a reload the dice (or roll) command will be available in-game.
""" """
from builtins import range
import re import re
from random import randint from random import randint

View file

@ -40,7 +40,8 @@ example of usage.
For a simple demonstration, add `CmdMenuTest` from this module to the default cmdset. For a simple demonstration, add `CmdMenuTest` from this module to the default cmdset.
""" """
from builtins import object from builtins import object, range
from types import MethodType from types import MethodType
from evennia import syscmdkeys from evennia import syscmdkeys

View file

@ -90,6 +90,7 @@ Usage:
that never change (if this is desired). that never change (if this is desired).
""" """
from builtins import range
import re import re
from random import choice, randint from random import choice, randint

View file

@ -10,7 +10,8 @@ menu. Run the script with the -h flag to see usage information.
""" """
from __future__ import print_function from __future__ import print_function
from builtins import input from builtins import input, range
import os import os
import sys import sys
import signal import signal

View file

@ -32,6 +32,7 @@ for instructions on how to define this module.
""" """
from __future__ import print_function from __future__ import print_function
from __future__ import division from __future__ import division
from builtins import range
import sys import sys
import time import time

View file

@ -12,6 +12,7 @@ value - which may change as Evennia is developed. This way you can
always be sure of what you have changed and what is default behaviour. always be sure of what you have changed and what is default behaviour.
""" """
from builtins import range
import os import os
import sys import sys

View file

@ -13,7 +13,8 @@ it is run by Evennia just before returning data to/from the
user. user.
""" """
from builtins import object from builtins import object, range
import re import re
from evennia.utils import utils from evennia.utils import utils
from evennia.utils.utils import to_str, to_unicode from evennia.utils.utils import to_str, to_unicode
@ -770,7 +771,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
# Check between the slice intervals for escape sequences. # Check between the slice intervals for escape sequences.
i = None i = None
for i in slice_indexes[1:]: for i in slice_indexes[1:]:
for index in xrange(last_mark, i): for index in range(last_mark, i):
if index in self._code_indexes: if index in self._code_indexes:
string += self._raw_string[index] string += self._raw_string[index]
last_mark = i last_mark = i
@ -810,7 +811,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
result = '' result = ''
# Get the character they're after, and replay all escape sequences # Get the character they're after, and replay all escape sequences
# previous to it. # previous to it.
for index in xrange(0, item + 1): for index in range(0, item + 1):
if index in self._code_indexes: if index in self._code_indexes:
result += self._raw_string[index] result += self._raw_string[index]
return ANSIString(result + clean + append_tail, decoded=True) return ANSIString(result + clean + append_tail, decoded=True)
@ -878,7 +879,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
code_indexes.extend(range(match.start(), match.end())) code_indexes.extend(range(match.start(), match.end()))
if not code_indexes: if not code_indexes:
# Plain string, no ANSI codes. # Plain string, no ANSI codes.
return code_indexes, range(0, len(self._raw_string)) return code_indexes, list(range(0, len(self._raw_string)))
# all indexes not occupied by ansi codes are normal characters # all indexes not occupied by ansi codes are normal characters
char_indexes = [i for i in range(len(self._raw_string)) if i not in code_indexes] char_indexes = [i for i in range(len(self._raw_string)) if i not in code_indexes]
return code_indexes, char_indexes return code_indexes, char_indexes
@ -1007,7 +1008,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
if not isinstance(char, ANSIString): if not isinstance(char, ANSIString):
line = char * amount line = char * amount
return ANSIString( return ANSIString(
char * amount, code_indexes=[], char_indexes=range(0, len(line)), char * amount, code_indexes=[], char_indexes=list(range(0, len(line))),
clean_string=char) clean_string=char)
try: try:
start = char._code_indexes[0] start = char._code_indexes[0]
@ -1020,7 +1021,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
code_indexes = [i for i in range(0, len(prefix))] code_indexes = [i for i in range(0, len(prefix))]
length = len(prefix) + len(line) length = len(prefix) + len(line)
code_indexes.extend([i for i in range(length, length + len(postfix))]) code_indexes.extend([i for i in range(length, length + len(postfix))])
char_indexes = self._shifter(xrange(0, len(line)), len(prefix)) char_indexes = self._shifter(range(0, len(line)), len(prefix))
raw_string = prefix + line + postfix raw_string = prefix + line + postfix
return ANSIString( return ANSIString(
raw_string, clean_string=line, char_indexes=char_indexes, raw_string, clean_string=line, char_indexes=char_indexes,

View file

@ -135,7 +135,7 @@ form will raise an error.
""" """
from __future__ import print_function from __future__ import print_function
from builtins import object from builtins import object, range
import re import re
import copy import copy

View file

@ -134,7 +134,7 @@ evennia.utils.evmenu`.
""" """
from __future__ import print_function from __future__ import print_function
from builtins import object from builtins import object, range
from textwrap import dedent from textwrap import dedent
from inspect import isfunction, getargspec from inspect import isfunction, getargspec
@ -271,13 +271,13 @@ def evtable_options_formatter(optionlist):
ncols = ncols + 1 if nlastcol > 0 else ncols ncols = ncols + 1 if nlastcol > 0 else ncols
if ncols > 1: if ncols > 1:
# only extend if longer than one column # only extend if longer than one column
table.extend([" " for i in xrange(nrows - nlastcol)]) table.extend([" " for i in range(nrows - nlastcol)])
# build the actual table grid # build the actual table grid
table = [table[icol * nrows : (icol * nrows) + nrows] for icol in xrange(0, ncols)] table = [table[icol * nrows : (icol * nrows) + nrows] for icol in range(0, ncols)]
# adjust the width of each column # adjust the width of each column
for icol in xrange(len(table)): for icol in range(len(table)):
col_width = max(max(m_len(p) for p in part.split("\n")) for part in table[icol]) + colsep col_width = max(max(m_len(p) for p in part.split("\n")) for part in table[icol]) + colsep
table[icol] = [pad(part, width=col_width + colsep, align="l") for part in table[icol]] table[icol] = [pad(part, width=col_width + colsep, align="l") for part in table[icol]]

View file

@ -25,7 +25,7 @@ long enough to need to scroll and **kwargs will be passed on to the
caller.msg() construct (text will be using the pager restrictor). caller.msg() construct (text will be using the pager restrictor).
""" """
from builtins import object from builtins import object, range
from django.conf import settings from django.conf import settings
from evennia import Command, CmdSet from evennia import Command, CmdSet

View file

@ -115,7 +115,8 @@ table string.
""" """
from __future__ import print_function from __future__ import print_function
from builtins import object from builtins import object, range
#from textwrap import wrap #from textwrap import wrap
from django.conf import settings from django.conf import settings
from textwrap import TextWrapper from textwrap import TextWrapper
@ -524,7 +525,7 @@ class EvCell(object):
adjusted_data[-1] = adjusted_data[-1][:-2] + ".." adjusted_data[-1] = adjusted_data[-1][:-2] + ".."
elif excess < 0: elif excess < 0:
# too few lines. Fill to height. # too few lines. Fill to height.
adjusted_data.extend(["" for i in xrange(excess)]) adjusted_data.extend(["" for i in range(excess)])
return adjusted_data return adjusted_data
@ -600,11 +601,11 @@ class EvCell(object):
return data return data
# only care if we need to add new lines # only care if we need to add new lines
if valign == 't': if valign == 't':
return data + [padline for i in xrange(excess)] return data + [padline for i in range(excess)]
elif valign == 'b': elif valign == 'b':
return [padline for i in xrange(excess)] + data return [padline for i in range(excess)] + data
else: # center else: # center
narrowside = [padline for i in xrange(excess // 2)] narrowside = [padline for i in range(excess // 2)]
widerside = narrowside + [padline] widerside = narrowside + [padline]
if excess % 2: if excess % 2:
# uneven padding # uneven padding
@ -630,8 +631,8 @@ class EvCell(object):
left = self.hpad_char * self.pad_left left = self.hpad_char * self.pad_left
right = self.hpad_char * self.pad_right right = self.hpad_char * self.pad_right
vfill = (self.width + self.pad_left + self.pad_right) * self.vpad_char vfill = (self.width + self.pad_left + self.pad_right) * self.vpad_char
top = [vfill for i in xrange(self.pad_top)] top = [vfill for i in range(self.pad_top)]
bottom = [vfill for i in xrange(self.pad_bottom)] bottom = [vfill for i in range(self.pad_bottom)]
return top + [left + line + right for line in data] + bottom return top + [left + line + right for line in data] + bottom
def _border(self, data): def _border(self, data):
@ -655,12 +656,12 @@ class EvCell(object):
vfill = self.corner_top_left_char if left else "" vfill = self.corner_top_left_char if left else ""
vfill += cwidth * self.border_top_char vfill += cwidth * self.border_top_char
vfill += self.corner_top_right_char if right else "" vfill += self.corner_top_right_char if right else ""
top = [vfill for i in xrange(self.border_top)] top = [vfill for i in range(self.border_top)]
vfill = self.corner_bottom_left_char if left else "" vfill = self.corner_bottom_left_char if left else ""
vfill += cwidth * self.border_bottom_char vfill += cwidth * self.border_bottom_char
vfill += self.corner_bottom_right_char if right else "" vfill += self.corner_bottom_right_char if right else ""
bottom = [vfill for i in xrange(self.border_bottom)] bottom = [vfill for i in range(self.border_bottom)]
return top + [left + line + right for line in data] + bottom return top + [left + line + right for line in data] + bottom
@ -1020,10 +1021,10 @@ class EvTable(object):
excess = len(header) - len(table) excess = len(header) - len(table)
if excess > 0: if excess > 0:
# header bigger than table # header bigger than table
table.extend([] for i in xrange(excess)) table.extend([] for i in range(excess))
elif excess < 0: elif excess < 0:
# too short header # too short header
header.extend(_to_ansi(["" for i in xrange(abs(excess))])) header.extend(_to_ansi(["" for i in range(abs(excess))]))
for ix, heading in enumerate(header): for ix, heading in enumerate(header):
table[ix].insert(0, heading) table[ix].insert(0, heading)
else: else:
@ -1217,7 +1218,7 @@ class EvTable(object):
self.worktable[icol].reformat(**options) self.worktable[icol].reformat(**options)
if nrow < nrowmax: if nrow < nrowmax:
# add more rows to too-short columns # add more rows to too-short columns
empty_rows = ["" for i in xrange(nrowmax-nrow)] empty_rows = ["" for i in range(nrowmax-nrow)]
self.worktable[icol].add_rows(*empty_rows) self.worktable[icol].add_rows(*empty_rows)
self.ncols = ncols self.ncols = ncols
self.nrows = nrowmax self.nrows = nrowmax
@ -1247,14 +1248,14 @@ class EvTable(object):
excess = width - cwmin excess = width - cwmin
if self.evenwidth: if self.evenwidth:
# make each collumn of equal width # make each collumn of equal width
for i in xrange(excess): for i in range(excess):
# flood-fill the minimum table starting with the smallest collumns # flood-fill the minimum table starting with the smallest collumns
ci = cwidths_min.index(min(cwidths_min)) ci = cwidths_min.index(min(cwidths_min))
cwidths_min[ci] += 1 cwidths_min[ci] += 1
cwidths = cwidths_min cwidths = cwidths_min
else: else:
# make each collumn expand more proportional to their data size # make each collumn expand more proportional to their data size
for i in xrange(excess): for i in range(excess):
# fill wider collumns first # fill wider collumns first
ci = cwidths.index(max(cwidths)) ci = cwidths.index(max(cwidths))
cwidths_min[ci] += 1 cwidths_min[ci] += 1
@ -1270,14 +1271,14 @@ class EvTable(object):
raise #Exception ("Error in horizontal allign:\n %s" % msg) raise #Exception ("Error in horizontal allign:\n %s" % msg)
# equalize heights for each row (we must do this here, since it may have changed to fit new widths) # equalize heights for each row (we must do this here, since it may have changed to fit new widths)
cheights = [max(cell.get_height() for cell in (col[iy] for col in self.worktable)) for iy in xrange(nrowmax)] cheights = [max(cell.get_height() for cell in (col[iy] for col in self.worktable)) for iy in range(nrowmax)]
if self.height: if self.height:
# if we are fixing the table height, it means cells must crop text instead of resizing. # if we are fixing the table height, it means cells must crop text instead of resizing.
if nrowmax: if nrowmax:
# get minimum possible cell heights for each collumn # get minimum possible cell heights for each collumn
cheights_min = [max(cell.get_min_height() for cell in (col[iy] for col in self.worktable)) for iy in xrange(nrowmax)] cheights_min = [max(cell.get_min_height() for cell in (col[iy] for col in self.worktable)) for iy in range(nrowmax)]
chmin = sum(cheights_min) chmin = sum(cheights_min)
if chmin > self.height: if chmin > self.height:
@ -1290,7 +1291,7 @@ class EvTable(object):
excess = self.height - chmin excess = self.height - chmin
even = self.height % 2 == 0 even = self.height % 2 == 0
for i in xrange(excess): for i in range(excess):
# expand the cells with the most rows first # expand the cells with the most rows first
if 0 <= i < nrowmax and nrowmax > 1: if 0 <= i < nrowmax and nrowmax > 1:
# avoid adding to header first round (looks bad on very small tables) # avoid adding to header first round (looks bad on very small tables)
@ -1327,12 +1328,12 @@ class EvTable(object):
This will also balance the table. This will also balance the table.
""" """
self._balance() self._balance()
for iy in xrange(self.nrows): for iy in range(self.nrows):
cell_row = [col[iy] for col in self.worktable] cell_row = [col[iy] for col in self.worktable]
# this produces a list of lists, each of equal length # this produces a list of lists, each of equal length
cell_data = [cell.get() for cell in cell_row] cell_data = [cell.get() for cell in cell_row]
cell_height = min(len(lines) for lines in cell_data) cell_height = min(len(lines) for lines in cell_data)
for iline in xrange(cell_height): for iline in range(cell_height):
yield ANSIString("").join(_to_ansi(celldata[iline] for celldata in cell_data)) yield ANSIString("").join(_to_ansi(celldata[iline] for celldata in cell_data))
def add_header(self, *args, **kwargs): def add_header(self, *args, **kwargs):
@ -1383,12 +1384,12 @@ class EvTable(object):
if excess > 0: if excess > 0:
# we need to add new rows to table # we need to add new rows to table
for col in self.table: for col in self.table:
empty_rows = ["" for i in xrange(excess)] empty_rows = ["" for i in range(excess)]
col.add_rows(*empty_rows, **options) col.add_rows(*empty_rows, **options)
self.nrows += excess self.nrows += excess
elif excess < 0: elif excess < 0:
# we need to add new rows to new column # we need to add new rows to new column
empty_rows = ["" for i in xrange(abs(excess))] empty_rows = ["" for i in range(abs(excess))]
column.add_rows(*empty_rows, **options) column.add_rows(*empty_rows, **options)
self.nrows -= excess self.nrows -= excess
@ -1440,12 +1441,12 @@ class EvTable(object):
if excess > 0: if excess > 0:
# we need to add new empty columns to table # we need to add new empty columns to table
empty_rows = ["" for i in xrange(htable)] empty_rows = ["" for i in range(htable)]
self.table.extend([EvColumn(*empty_rows, **options) for i in xrange(excess)]) self.table.extend([EvColumn(*empty_rows, **options) for i in range(excess)])
self.ncols += excess self.ncols += excess
elif excess < 0: elif excess < 0:
# we need to add more cells to row # we need to add more cells to row
row.extend(["" for i in xrange(abs(excess))]) row.extend(["" for i in range(abs(excess))])
self.ncols -= excess self.ncols -= excess
if ypos is None or ypos > htable - 1: if ypos is None or ypos > htable - 1:

View file

@ -1,4 +1,6 @@
from __future__ import absolute_import from __future__ import absolute_import
from builtins import range
from django.test import TestCase from django.test import TestCase
from .models import SharedMemoryModel from .models import SharedMemoryModel
@ -29,7 +31,7 @@ class SharedMemorysTest(TestCase):
category = Category.objects.create(name="Category %d" % (n,)) category = Category.objects.create(name="Category %d" % (n,))
regcategory = RegularCategory.objects.create(name="Category %d" % (n,)) regcategory = RegularCategory.objects.create(name="Category %d" % (n,))
for n in xrange(0, 10): for n in range(0, 10):
Article.objects.create(name="Article %d" % (n,), category=category, category2=regcategory) Article.objects.create(name="Article %d" % (n,), category=category, category2=regcategory)
RegularArticle.objects.create(name="Article %d" % (n,), category=category, category2=regcategory) RegularArticle.objects.create(name="Article %d" % (n,), category=category, category2=regcategory)

View file

@ -30,7 +30,8 @@
# POSSIBILITY OF SUCH DAMAGE. # POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function from __future__ import print_function
from builtins import object from builtins import object, range
__version__ = "trunk" __version__ = "trunk"
import copy import copy

View file

@ -1,3 +1,5 @@
from builtins import range
import re import re
try: try:

View file

@ -22,6 +22,7 @@
Blind reimplementation of WebSockets as a standalone wrapper for Twisted Blind reimplementation of WebSockets as a standalone wrapper for Twisted
protocols. protocols.
""" """
from builtins import range
__version__ = "0.7.1" __version__ = "0.7.1"
@ -53,18 +54,18 @@ class WSException(Exception):
# RFC6455 - RFC 6455. The official WebSocket protocol standard. The protocol # RFC6455 - RFC 6455. The official WebSocket protocol standard. The protocol
# number is 13, but otherwise it is identical to HyBi-07. # number is 13, but otherwise it is identical to HyBi-07.
HYBI00, HYBI07, HYBI10, RFC6455 = range(4) HYBI00, HYBI07, HYBI10, RFC6455 = list(range(4))
# States of the state machine. Because there are no reliable byte counts for # States of the state machine. Because there are no reliable byte counts for
# any of this, we don't use StatefulProtocol; instead, we use custom state # any of this, we don't use StatefulProtocol; instead, we use custom state
# enumerations. Yay! # enumerations. Yay!
REQUEST, NEGOTIATING, CHALLENGE, FRAMES = range(4) REQUEST, NEGOTIATING, CHALLENGE, FRAMES = list(range(4))
# Control frame specifiers. Some versions of WS have control signals sent # Control frame specifiers. Some versions of WS have control signals sent
# in-band. Adorable, right? # in-band. Adorable, right?
NORMAL, CLOSE, PING, PONG = range(4) NORMAL, CLOSE, PING, PONG = list(range(4))
opcode_types = { opcode_types = {
0x0: NORMAL, 0x0: NORMAL,

View file

@ -5,9 +5,8 @@ They provide some useful string and conversion methods that might
be of use when designing your own game. be of use when designing your own game.
""" """
from __future__ import division from __future__ import division, print_function
from __future__ import print_function from builtins import object, range
from builtins import object
import os import os
import sys import sys