Skip to content

Commit

Permalink
Build table strings using cStringIO, for best performance with large …
Browse files Browse the repository at this point in the history
…tables.
  • Loading branch information
lmaurits committed May 16, 2012
1 parent 7f0888b commit 3bf3201
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
30 changes: 21 additions & 9 deletions prettytable.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@

__version__ = "TRUNK"

import sys
import copy
import cStringIO
import random
import sys
import textwrap

py3k = sys.version_info[0] >= 3
Expand Down Expand Up @@ -751,7 +752,10 @@ def _get_rows(self, options):
# Undecorate
rows = [row[1:] for row in rows]
return rows


def _format_rows(self, rows, options):
return rows

##############################
# PLAIN TEXT STRING METHODS #
##############################
Expand Down Expand Up @@ -782,7 +786,7 @@ def get_string(self, **kwargs):

options = self._get_options(kwargs)

bits = []
string = cStringIO.StringIO()

# Don't think too hard about an empty table
if self.rowcount == 0:
Expand All @@ -791,29 +795,36 @@ def get_string(self, **kwargs):
rows = self._get_rows(options)
self._compute_widths(rows, options)

formatted_rows = self._format_rows(rows, options)

# Build rows
# (for now, this is done before building headers etc. because rowbits.append
# contains width-adjusting voodoo which has to be done first. This is ugly
# and Wrong and will change soon)
rowbits = []
for row in rows:
for row in formatted_rows:
rowbits.append(self._stringify_row(row, options))


# Add header or top of border
if options["header"]:
bits.append(self._stringify_header(options))
string.write(self._stringify_header(options))
# string.write("\n")
elif options["border"] and options["hrules"] != NONE:
bits.append(self._hrule)
string.write(self._hrule)
# string.write("\n")

# Add rows
bits.extend(rowbits)
for rowbit in rowbits:
string.write("\n")
string.write(rowbit)

# Add bottom of border
if options["border"] and not options["hrules"]:
bits.append(self._hrule)
string.write("\n")
string.write(self._hrule)

string = "\n".join(bits)
string = string.getvalue()
self._nonunicode = string
return _unicode(string)

Expand All @@ -828,6 +839,7 @@ def _stringify_hrule(self, options):
continue
bits.append((width+lpad+rpad)*options["horizontal_char"])
bits.append(options["junction_char"])
# bits.append("\n")
return "".join(bits)

def _stringify_header(self, options):
Expand Down
2 changes: 1 addition & 1 deletion prettytable_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def setUp(self):

class OptionOverrideTests(CityDataTest):

"""Make sure all options are properly overwritten by printt."""
"""Make sure all options are properly overwritten by get_string."""

def testBorder(self):
default = self.x.get_string()
Expand Down

0 comments on commit 3bf3201

Please sign in to comment.