summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKane Blueriver <kxxoling@gmail.com>2015-04-28 18:16:42 +0800
committerKane Blueriver <kxxoling@gmail.com>2015-04-28 18:16:42 +0800
commit1ed7f229db4a4853dd654009f247edf48ec6ed62 (patch)
tree686eedc97e48cd1c612542e409c809dbad9996f6
parentdcc65ceef4352cbf2c664fb5f2837074b24eb7f7 (diff)
downloadpython-prettytable-ptable-1ed7f229db4a4853dd654009f247edf48ec6ed62.tar.gz
Reformat
-rw-r--r--README.rst174
-rw-r--r--prettytable.py190
-rw-r--r--prettytable_test.py88
-rw-r--r--setup.py2
4 files changed, 243 insertions, 211 deletions
diff --git a/README.rst b/README.rst
index 76b0c9c..dcd7c9a 100644
--- a/README.rst
+++ b/README.rst
@@ -17,8 +17,8 @@ and you want to put some data into it. You have a few options.
== Row by row ==
-You can add data one row at a time. To do this you can set the field names
-first using the `field_names` attribute, and then add the rows one at a time
+You can add data one row at a time. To do this you can set the field names
+first using the `field_names` attribute, and then add the rows one at a time
using the `add_row` method:
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
@@ -32,26 +32,26 @@ x.add_row(["Perth", 5386, 1554769, 869.4])
== Column by column ==
-You can add data one column at a time as well. To do this you use the
-`add_column` method, which takes two arguments - a string which is the name for
-the field the column you are adding corresponds to, and a list or tuple which
+You can add data one column at a time as well. To do this you use the
+`add_column` method, which takes two arguments - a string which is the name for
+the field the column you are adding corresponds to, and a list or tuple which
contains the column data"
-x.add_column("City name",
+x.add_column("City name",
["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"])
x.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
-x.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092,
+x.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092,
1554769])
-x.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9,
+x.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9,
869.4])
== Mixing and matching ==
-If you really want to, you can even mix and match `add_row` and `add_column`
-and build some of your table in one way and some of it in the other. There's a
-unit test which makes sure that doing things this way will always work out
-nicely as if you'd done it using just one of the two approaches. Tables built
-this way are kind of confusing for other people to read, though, so don't do
+If you really want to, you can even mix and match `add_row` and `add_column`
+and build some of your table in one way and some of it in the other. There's a
+unit test which makes sure that doing things this way will always work out
+nicely as if you'd done it using just one of the two approaches. Tables built
+this way are kind of confusing for other people to read, though, so don't do
this unless you have a good reason.
== Importing data from a CSV file ==
@@ -78,20 +78,20 @@ mytable = from_cursor(cursor)
== Getting data out ==
-There are three ways to get data out of a PrettyTable, in increasing order of
+There are three ways to get data out of a PrettyTable, in increasing order of
completeness:
* The `del_row` method takes an integer index of a single row to delete.
- * The `clear_rows` method takes no arguments and deletes all the rows in the
-table - but keeps the field names as they were so you that you can repopulate
+ * The `clear_rows` method takes no arguments and deletes all the rows in the
+table - but keeps the field names as they were so you that you can repopulate
it with the same kind of data.
- * The `clear` method takes no arguments and deletes all rows and all field
-names. It's not quite the same as creating a fresh table instance, though -
+ * The `clear` method takes no arguments and deletes all rows and all field
+names. It's not quite the same as creating a fresh table instance, though -
style related settings, discussed later, are maintained.
= Displaying your table in ASCII form =
-PrettyTable's main goal is to let you print tables in an attractive ASCII form,
+PrettyTable's main goal is to let you print tables in an attractive ASCII form,
like this:
+-----------+------+------------+-----------------+
@@ -106,7 +106,7 @@ like this:
| Sydney | 2058 | 4336374 | 1214.8 |
+-----------+------+------------+-----------------+
-You can print tables like this to `stdout` or get string representations of
+You can print tables like this to `stdout` or get string representations of
them.
== Printing ==
@@ -130,14 +130,14 @@ print x.get_string()
== Stringing ==
-If you don't want to actually print your table in ASCII form but just get a
-string containing what _would_ be printed if you use "print x", you can use
+If you don't want to actually print your table in ASCII form but just get a
+string containing what _would_ be printed if you use "print x", you can use
the `get_string` method:
mystring = x.get_string()
-This string is guaranteed to look exactly the same as what would be printed by
-doing "print x". You can now do all the usual things you can do with a
+This string is guaranteed to look exactly the same as what would be printed by
+doing "print x". You can now do all the usual things you can do with a
string, like write your table to a file or insert it into a GUI.
== Controlling which data gets displayed ==
@@ -145,7 +145,7 @@ string, like write your table to a file or insert it into a GUI.
If you like, you can restrict the output of `print x` or `x.get_string` to
only the fields or rows you like.
-The `fields` argument to these methods takes a list of field names to be
+The `fields` argument to these methods takes a list of field names to be
printed:
print x.get_string(fields=["City name", "Population"])
@@ -164,10 +164,10 @@ gives:
| Sydney | 4336374 |
+-----------+------------+
-The `start` and `end` arguments take the index of the first and last row to
-print respectively. Note that the indexing works like Python list slicing - to
-print the 2nd, 3rd and 4th rows of the table, set `start` to 1 (the first row
-is row 0, so the second is row 1) and set `end` to 4 (the index of the 4th row,
+The `start` and `end` arguments take the index of the first and last row to
+print respectively. Note that the indexing works like Python list slicing - to
+print the 2nd, 3rd and 4th rows of the table, set `start` to 1 (the first row
+is row 0, so the second is row 1) and set `end` to 4 (the index of the 4th row,
plus 1):
print x.get_string(start=1,end=4)
@@ -188,8 +188,8 @@ By default, all columns in a table are centre aligned.
=== All columns at once ===
-You can change the alignment of all the columns in a table at once by assigning
-a one character string to the `align` attribute. The allowed strings are "l",
+You can change the alignment of all the columns in a table at once by assigning
+a one character string to the `align` attribute. The allowed strings are "l",
"r" and "c" for left, right and centre alignment, respectively:
x.align = "r"
@@ -211,8 +211,8 @@ gives:
=== One column at a time ===
-You can also change the alignment of individual columns based on the
-corresponding field name by treating the `align` attribute as if it were a
+You can also change the alignment of individual columns based on the
+corresponding field name by treating the `align` attribute as if it were a
dictionary.
x.align["City name"] = "l"
@@ -237,11 +237,11 @@ gives:
== Sorting your table by a field ==
-You can make sure that your ASCII tables are produced with the data sorted by
+You can make sure that your ASCII tables are produced with the data sorted by
one particular field by giving `get_string` a `sortby` keyword argument, which
must be a string containing the name of one field.
-For example, to print the example table we built earlier of Australian capital
+For example, to print the example table we built earlier of Australian capital
city data, so that the most populated city comes last, we can do this:
print x.get_string(sortby="Population")
@@ -260,10 +260,10 @@ to get
| Sydney | 2058 | 4336374 | 1214.8 |
+-----------+------+------------+-----------------+
-If we want the most populated city to come _first_, we can also give a
+If we want the most populated city to come _first_, we can also give a
`reversesort=True` argument.
-If you _always_ want your tables to be sorted in a certain way, you can make
+If you _always_ want your tables to be sorted in a certain way, you can make
the setting long term like this:
x.sortby = "Population"
@@ -271,8 +271,8 @@ print x
print x
print x
-All three tables printed by this code will be sorted by population (you could
-do `x.reversesort = True` as well, if you wanted). The behaviour will persist
+All three tables printed by this code will be sorted by population (you could
+do `x.reversesort = True` as well, if you wanted). The behaviour will persist
until you turn it off:
x.sortby = None
@@ -289,80 +289,80 @@ instance of the data in the `sort_by` column.
= Changing the appearance of your table - the easy way =
-By default, PrettyTable produces ASCII tables that look like the ones used in
-SQL database shells. But if can print them in a variety of other formats as
-well. If the format you want to use is common, PrettyTable makes this very
-easy for you to do using the `set_style` method. If you want to produce an
+By default, PrettyTable produces ASCII tables that look like the ones used in
+SQL database shells. But if can print them in a variety of other formats as
+well. If the format you want to use is common, PrettyTable makes this very
+easy for you to do using the `set_style` method. If you want to produce an
uncommon table, you'll have to do things slightly harder (see later).
== Setting a table style ==
-You can set the style for your table using the `set_style` method before any
-calls to `print` or `get_string`. Here's how to print a table in a format
+You can set the style for your table using the `set_style` method before any
+calls to `print` or `get_string`. Here's how to print a table in a format
which works nicely with Microsoft Word's "Convert to table" feature:
from prettytable import MSWORD_FRIENDLY
x.set_style(MSWORD_FRIENDLY)
print x
-In addition to `MSWORD_FRIENDLY` there are currently two other in-built styles
+In addition to `MSWORD_FRIENDLY` there are currently two other in-built styles
you can use for your tables:
- * `DEFAULT` - The default look, used to undo any style changes you may have
+ * `DEFAULT` - The default look, used to undo any style changes you may have
made
- * `PLAIN_COLUMN` - A borderless style that works well with command line
+ * `PLAIN_COLUMN` - A borderless style that works well with command line
programs for columnar data
Other styles are likely to appear in future releases.
= Changing the appearance of your table - the hard way =
-If you want to display your table in a style other than one of the in-built
+If you want to display your table in a style other than one of the in-built
styles listed above, you'll have to set things up the hard way.
Don't worry, it's not really that hard!
== Style options ==
-PrettyTable has a number of style options which control various aspects of how
-tables are displayed. You have the freedom to set each of these options
-individually to whatever you prefer. The `set_style` method just does this
+PrettyTable has a number of style options which control various aspects of how
+tables are displayed. You have the freedom to set each of these options
+individually to whatever you prefer. The `set_style` method just does this
automatically for you.
The options are these:
- * `border` - A boolean option (must be `True` or `False`). Controls whether
+ * `border` - A boolean option (must be `True` or `False`). Controls whether
or not a border is drawn around the table.
- * `header` - A boolean option (must be `True` or `False`). Controls whether
- or not the first row of the table is a header showing the names of all the
+ * `header` - A boolean option (must be `True` or `False`). Controls whether
+ or not the first row of the table is a header showing the names of all the
fields.
- * `hrules` - Controls printing of horizontal rules after rows. Allowed
+ * `hrules` - Controls printing of horizontal rules after rows. Allowed
values: FRAME, HEADER, ALL, NONE - note that these are variables defined
inside the `prettytable` module so make sure you import them or use
`prettytable.FRAME` etc.
- * `vrules` - Controls printing of vertical rules between columns. Allowed
+ * `vrules` - Controls printing of vertical rules between columns. Allowed
values: FRAME, ALL, NONE.
* `int_format` - A string which controls the way integer data is printed.
This works like: print "%<int_format>d" % data
* `float_format` - A string which controls the way floating point data is
printed. This works like: print "%<int_format>f" % data
- * `padding_width` - Number of spaces on either side of column data (only used
+ * `padding_width` - Number of spaces on either side of column data (only used
if left and right paddings are None).
* `left_padding_width` - Number of spaces on left hand side of column data.
* `right_padding_width` - Number of spaces on right hand side of column data.
- * `vertical_char` - Single character string used to draw vertical lines.
+ * `vertical_char` - Single character string used to draw vertical lines.
Default is `|`.
- * `horizontal_char` - Single character string used to draw horizontal lines.
+ * `horizontal_char` - Single character string used to draw horizontal lines.
Default is `-`.
- * `junction_char` - Single character string used to draw line junctions.
+ * `junction_char` - Single character string used to draw line junctions.
Default is `+`.
You can set the style options to your own settings in two ways:
== Setting style options for the long term ==
-If you want to print your table with a different style several times, you can
-set your option for the "long term" just by changing the appropriate
+If you want to print your table with a different style several times, you can
+set your option for the "long term" just by changing the appropriate
attributes. If you never want your tables to have borders you can do this:
x.border = False
@@ -370,18 +370,18 @@ print x
print x
print x
-Neither of the 3 tables printed by this will have borders, even if you do
-things like add extra rows inbetween them. The lack of borders will last until
+Neither of the 3 tables printed by this will have borders, even if you do
+things like add extra rows inbetween them. The lack of borders will last until
you do:
x.border = True
-to turn them on again. This sort of long term setting is exactly how
-`set_style` works. `set_style` just sets a bunch of attributes to pre-set
+to turn them on again. This sort of long term setting is exactly how
+`set_style` works. `set_style` just sets a bunch of attributes to pre-set
values for you.
-Note that if you know what style options you want at the moment you are
-creating your table, you can specify them using keyword arguments to the
+Note that if you know what style options you want at the moment you are
+creating your table, you can specify them using keyword arguments to the
constructor. For example, the following two code blocks are equivalent:
x = PrettyTable()
@@ -393,9 +393,9 @@ x = PrettyTable(border=False, header=False, padding_width=5)
== Changing style options just once ==
-If you don't want to make long term style changes by changing an attribute like
-in the previous section, you can make changes that last for just one
-``get_string`` by giving those methods keyword arguments. To print two
+If you don't want to make long term style changes by changing an attribute like
+in the previous section, you can make changes that last for just one
+``get_string`` by giving those methods keyword arguments. To print two
"normal" tables with one borderless table between them, you could do this:
print x
@@ -404,15 +404,15 @@ print x
= Displaying your table in HTML form =
-PrettyTable will also print your tables in HTML form, as `<table>`s. Just like
-in ASCII form, you can actually print your table - just use `print_html()` - or
-get a string representation - just use `get_html_string()`. HTML printing
-supports the `fields`, `start`, `end`, `sortby` and `reversesort` arguments in
+PrettyTable will also print your tables in HTML form, as `<table>`s. Just like
+in ASCII form, you can actually print your table - just use `print_html()` - or
+get a string representation - just use `get_html_string()`. HTML printing
+supports the `fields`, `start`, `end`, `sortby` and `reversesort` arguments in
exactly the same way as ASCII printing.
== Styling HTML tables ==
-By default, PrettyTable outputs HTML for "vanilla" tables. The HTML code is
+By default, PrettyTable outputs HTML for "vanilla" tables. The HTML code is
quite simple. It looks like this:
<table>
@@ -437,25 +437,25 @@ quite simple. It looks like this:
...
</table>
-If you like, you can ask PrettyTable to do its best to mimick the style options
-that your table has set using inline CSS. This is done by giving a
-`format=True` keyword argument to either the `print_html` or `get_html_string`
+If you like, you can ask PrettyTable to do its best to mimick the style options
+that your table has set using inline CSS. This is done by giving a
+`format=True` keyword argument to either the `print_html` or `get_html_string`
methods. Note that if you _always_ want to print formatted HTML you can do:
x.format = True
and the setting will persist until you turn it off.
-Just like with ASCII tables, if you want to change the table's style for just
-one `print_html` or one `get_html_string` you can pass those methods keyword
+Just like with ASCII tables, if you want to change the table's style for just
+one `print_html` or one `get_html_string` you can pass those methods keyword
arguments - exactly like `print` and `get_string`.
== Setting HTML attributes ==
-You can provide a dictionary of HTML attribute name/value pairs to the
-`print_html` and `get_html_string` methods using the `attributes` keyword
-argument. This lets you specify common HTML attributes like `name`, `id` and
-`class` that can be used for linking to your tables or customising their
+You can provide a dictionary of HTML attribute name/value pairs to the
+`print_html` and `get_html_string` methods using the `attributes` keyword
+argument. This lets you specify common HTML attributes like `name`, `id` and
+`class` that can be used for linking to your tables or customising their
appearance using CSS. For example:
x.print_html(attributes={"name":"my_table", "class":"red_table"})
@@ -478,7 +478,7 @@ will print:
== Copying a table ==
-You can call the `copy` method on a PrettyTable object without arguments to
+You can call the `copy` method on a PrettyTable object without arguments to
return an identical independent copy of the table.
If you want a copy of a PrettyTable object with just a subset of the rows,
diff --git a/prettytable.py b/prettytable.py
index d80acce..ba74d33 100644
--- a/prettytable.py
+++ b/prettytable.py
@@ -3,7 +3,7 @@
# Copyright (c) 2009-2014, Luke Maurits <luke@maurits.id.au>
# All rights reserved.
# With contributions from:
-# * Chris Clark
+# * Chris Clark
# * Klein Stephane
# * John Filleau
#
@@ -63,8 +63,8 @@ else:
# hrule styles
FRAME = 0
-ALL = 1
-NONE = 2
+ALL = 1
+NONE = 2
HEADER = 3
# Table styles
@@ -75,14 +75,15 @@ RANDOM = 20
_re = re.compile("\033\[[0-9;]*m")
+
def _get_size(text):
lines = text.split("\n")
height = len(lines)
width = max([_str_block_width(line) for line in lines])
return (width, height)
-class PrettyTable(object):
+class PrettyTable(object):
def __init__(self, field_names=None, **kwargs):
"""Return a new PrettyTable instance
@@ -134,8 +135,10 @@ class PrettyTable(object):
# Options
self._options = "title start end fields header border sortby reversesort sort_key attributes format hrules vrules".split()
- self._options.extend("int_format float_format min_table_width max_table_width padding_width left_padding_width right_padding_width".split())
- self._options.extend("vertical_char horizontal_char junction_char header_style valign xhtml print_empty oldsortslice".split())
+ self._options.extend(
+ "int_format float_format min_table_width max_table_width padding_width left_padding_width right_padding_width".split())
+ self._options.extend(
+ "vertical_char horizontal_char junction_char header_style valign xhtml print_empty oldsortslice".split())
self._options.extend("align valign max_width min_width".split())
for option in self._options:
if option in kwargs:
@@ -215,15 +218,15 @@ class PrettyTable(object):
# Uneven padding
# Put more space on right if text is of odd length...
if _str_block_width(text) % 2:
- return (excess//2)*" " + text + (excess//2 + 1)*" "
+ return (excess // 2) * " " + text + (excess // 2 + 1) * " "
# and more space on left if text is of even length
else:
- return (excess//2 + 1)*" " + text + (excess//2)*" "
- # Why distribute extra space this way? To match the behaviour of
- # the inbuilt str.center() method.
+ return (excess // 2 + 1) * " " + text + (excess // 2) * " "
+ # Why distribute extra space this way? To match the behaviour of
+ # the inbuilt str.center() method.
else:
# Equal padding on either side
- return (excess//2)*" " + text + (excess//2)*" "
+ return (excess // 2) * " " + text + (excess // 2) * " "
def __getattr__(self, name):
@@ -244,7 +247,7 @@ class PrettyTable(object):
new = PrettyTable()
new.field_names = self.field_names
for attr in self._options:
- setattr(new, "_"+attr, getattr(self, "_"+attr))
+ setattr(new, "_" + attr, getattr(self, "_" + attr))
setattr(new, "_align", getattr(self, "_align"))
if isinstance(index, slice):
for row in self._rows[index]:
@@ -279,7 +282,8 @@ class PrettyTable(object):
def _validate_option(self, option, val):
if option in ("field_names"):
self._validate_field_names(val)
- elif option in ("start", "end", "max_width", "min_width", "min_table_width", "max_table_width", "padding_width", "left_padding_width", "right_padding_width", "format"):
+ elif option in ("start", "end", "max_width", "min_width", "min_table_width", "max_table_width", "padding_width",
+ "left_padding_width", "right_padding_width", "format"):
self._validate_nonnegative_int(option, val)
elif option in ("sortby"):
self._validate_field_name(option, val)
@@ -310,12 +314,14 @@ class PrettyTable(object):
try:
assert len(val) == len(self._field_names)
except AssertionError:
- raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._field_names)))
+ raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (
+ len(val), len(self._field_names)))
if self._rows:
try:
assert len(val) == len(self._rows[0])
except AssertionError:
- raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._rows[0])))
+ raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (
+ len(val), len(self._rows[0])))
# Check for uniqueness
try:
assert len(val) == len(set(val))
@@ -330,13 +336,13 @@ class PrettyTable(object):
def _validate_align(self, val):
try:
- assert val in ["l","c","r"]
+ assert val in ["l", "c", "r"]
except AssertionError:
raise Exception("Alignment %s is invalid, use l, c or r!" % val)
def _validate_valign(self, val):
try:
- assert val in ["t","m","b",None]
+ assert val in ["t", "m", "b", None]
except AssertionError:
raise Exception("Alignment %s is invalid, use t, m, b or None!" % val)
@@ -365,7 +371,6 @@ class PrettyTable(object):
if val == "":
return
try:
- assert type(val) in (str, unicode)
assert "." in val
bits = val.split(".")
assert len(bits) <= 2
@@ -449,6 +454,7 @@ class PrettyTable(object):
self._valign.pop(old_name)
else:
self.valign = "t"
+
@property
def align(self):
"""Controls alignment of fields
@@ -461,7 +467,7 @@ class PrettyTable(object):
def align(self, val):
if not self._field_names:
self._align = {}
- elif val is None or (isinstance(val,dict) and len(val) is 0):
+ elif val is None or (isinstance(val, dict) and len(val) is 0):
for field in self._field_names:
self._align[field] = "c"
else:
@@ -476,11 +482,12 @@ class PrettyTable(object):
valign - vertical alignment, one of "t", "m", or "b" """
return self._valign
+
@valign.setter
def valign(self, val):
if not self._field_names:
self._valign = {}
- elif val is None or (isinstance(val,dict) and len(val) is 0):
+ elif val is None or (isinstance(val, dict) and len(val) is 0):
for field in self._field_names:
self._valign[field] = "t"
else:
@@ -495,12 +502,13 @@ class PrettyTable(object):
max_width - maximum width integer"""
return self._max_width
+
@max_width.setter
def max_width(self, val):
- if val is None or (isinstance(val,dict) and len(val) is 0):
+ if val is None or (isinstance(val, dict) and len(val) is 0):
self._max_width = {}
else:
- self._validate_option("max_width",val)
+ self._validate_option("max_width", val)
for field in self._field_names:
self._max_width[field] = val
@@ -511,12 +519,13 @@ class PrettyTable(object):
min_width - minimum width integer"""
return self._min_width
+
@min_width.setter
def min_width(self, val):
- if val is None or (isinstance(val,dict) and len(val) is 0):
+ if val is None or (isinstance(val, dict) and len(val) is 0):
self._min_width = {}
else:
- self._validate_option("min_width",val)
+ self._validate_option("min_width", val)
for field in self._field_names:
self._min_width[field] = val
@@ -583,6 +592,7 @@ class PrettyTable(object):
end - index of last data row to include in output PLUS ONE (list slice style)"""
return self._end
+
@end.setter
def end(self, val):
self._validate_option("end", val)
@@ -596,6 +606,7 @@ class PrettyTable(object):
sortby - field name to sort by"""
return self._sortby
+
@sortby.setter
def sortby(self, val):
self._validate_option("sortby", val)
@@ -609,6 +620,7 @@ class PrettyTable(object):
reveresort - set to True to sort by descending order, or False to sort by ascending order"""
return self._reversesort
+
@reversesort.setter
def reversesort(self, val):
self._validate_option("reversesort", val)
@@ -622,6 +634,7 @@ class PrettyTable(object):
sort_key - a function which takes one argument and returns something to be sorted"""
return self._sort_key
+
@sort_key.setter
def sort_key(self, val):
self._validate_option("sort_key", val)
@@ -635,6 +648,7 @@ class PrettyTable(object):
header - print a header showing field names (True or False)"""
return self._header
+
@header.setter
def header(self, val):
self._validate_option("header", val)
@@ -648,6 +662,7 @@ class PrettyTable(object):
header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)"""
return self._header_style
+
@header_style.setter
def header_style(self, val):
self._validate_header_style(val)
@@ -661,6 +676,7 @@ class PrettyTable(object):
border - print a border around the table (True or False)"""
return self._border
+
@border.setter
def border(self, val):
self._validate_option("border", val)
@@ -674,6 +690,7 @@ class PrettyTable(object):
hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE"""
return self._hrules
+
@hrules.setter
def hrules(self, val):
self._validate_option("hrules", val)
@@ -687,6 +704,7 @@ class PrettyTable(object):
vrules - vertical rules style. Allowed values: FRAME, ALL, NONE"""
return self._vrules
+
@vrules.setter
def vrules(self, val):
self._validate_option("vrules", val)
@@ -699,12 +717,13 @@ class PrettyTable(object):
int_format - integer format string"""
return self._int_format
+
@int_format.setter
def int_format(self, val):
- if val is None or (isinstance(val,dict) and len(val) is 0):
+ if val is None or (isinstance(val, dict) and len(val) is 0):
self._int_format = {}
else:
- self._validate_option("int_format",val)
+ self._validate_option("int_format", val)
for field in self._field_names:
self._int_format[field] = val
@@ -715,12 +734,13 @@ class PrettyTable(object):
float_format - floating point format string"""
return self._float_format
+
@float_format.setter
def float_format(self, val):
- if val is None or (isinstance(val,dict) and len(val) is 0):
+ if val is None or (isinstance(val, dict) and len(val) is 0):
self._float_format = {}
else:
- self._validate_option("float_format",val)
+ self._validate_option("float_format", val)
for field in self._field_names:
self._float_format[field] = val
@@ -732,6 +752,7 @@ class PrettyTable(object):
padding_width - number of spaces, must be a positive integer"""
return self._padding_width
+
@padding_width.setter
def padding_width(self, val):
self._validate_option("padding_width", val)
@@ -745,6 +766,7 @@ class PrettyTable(object):
left_padding - number of spaces, must be a positive integer"""
return self._left_padding_width
+
@left_padding_width.setter
def left_padding_width(self, val):
self._validate_option("left_padding_width", val)
@@ -758,6 +780,7 @@ class PrettyTable(object):
right_padding - number of spaces, must be a positive integer"""
return self._right_padding_width
+
@right_padding_width.setter
def right_padding_width(self, val):
self._validate_option("right_padding_width", val)
@@ -771,6 +794,7 @@ class PrettyTable(object):
vertical_char - single character string used to draw vertical lines"""
return self._vertical_char
+
@vertical_char.setter
def vertical_char(self, val):
val = self._unicode(val)
@@ -785,6 +809,7 @@ class PrettyTable(object):
horizontal_char - single character string used to draw horizontal lines"""
return self._horizontal_char
+
@horizontal_char.setter
def horizontal_char(self, val):
val = self._unicode(val)
@@ -799,6 +824,7 @@ class PrettyTable(object):
junction_char - single character string used to draw line junctions"""
return self._junction_char
+
@junction_char.setter
def junction_char(self, val):
val = self._unicode(val)
@@ -813,6 +839,7 @@ class PrettyTable(object):
format - True or False"""
return self._format
+
@format.setter
def format(self, val):
self._validate_option("format", val)
@@ -826,6 +853,7 @@ class PrettyTable(object):
print_empty - True or False"""
return self._print_empty
+
@print_empty.setter
def print_empty(self, val):
self._validate_option("print_empty", val)
@@ -849,6 +877,7 @@ class PrettyTable(object):
def oldsortslice(self):
""" oldsortslice - Slice rows before sorting in the "old style" """
return self._oldsortslice
+
@oldsortslice.setter
def oldsortslice(self, val):
self._validate_option("oldsortslice", val)
@@ -866,7 +895,7 @@ class PrettyTable(object):
self._validate_option(option, kwargs[option])
options[option] = kwargs[option]
else:
- options[option] = getattr(self, "_"+option)
+ options[option] = getattr(self, "_" + option)
return options
##############################
@@ -924,8 +953,8 @@ class PrettyTable(object):
self.border = random.choice((True, False))
self._hrules = random.choice((ALL, FRAME, HEADER, NONE))
self._vrules = random.choice((ALL, FRAME, NONE))
- self.left_padding_width = random.randint(0,5)
- self.right_padding_width = random.randint(0,5)
+ self.left_padding_width = random.randint(0, 5)
+ self.right_padding_width = random.randint(0, 5)
self.vertical_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
self.horizontal_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
self.junction_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
@@ -944,9 +973,10 @@ class PrettyTable(object):
has fields"""
if self._field_names and len(row) != len(self._field_names):
- raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
+ raise Exception(
+ "Row has incorrect number of values, (actual) %d!=%d (expected)" % (len(row), len(self._field_names)))
if not self._field_names:
- self.field_names = [("Field %d" % (n+1)) for n in range(0,len(row))]
+ self.field_names = [("Field %d" % (n + 1)) for n in range(0, len(row))]
self._rows.append(list(row))
def del_row(self, row_index):
@@ -957,7 +987,7 @@ class PrettyTable(object):
row_index - The index of the row you want to delete. Indexing starts at 0."""
- if row_index > len(self._rows)-1:
+ if row_index > len(self._rows) - 1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
del self._rows[row_index]
@@ -980,7 +1010,7 @@ class PrettyTable(object):
self._align[fieldname] = align
self._valign[fieldname] = valign
for i in range(0, len(column)):
- if len(self._rows) < i+1:
+ if len(self._rows) < i + 1:
self._rows.append([])
self._rows[i].append(column[i])
else:
@@ -1048,14 +1078,14 @@ class PrettyTable(object):
table_width = self._compute_table_width(options)
if table_width > self._max_table_width:
# Shrink widths in proportion
- scale = 1.0*self._max_table_width / table_width
- widths = [int(math.floor(w*scale)) for w in widths]
+ scale = 1.0 * self._max_table_width / table_width
+ widths = [int(math.floor(w * scale)) for w in widths]
self._widths = widths
# Are we under min_table_width or title width?
if self._min_table_width or options["title"]:
if options["title"]:
- title_width = len(options["title"])+sum(self._get_padding_widths(options))
+ title_width = len(options["title"]) + sum(self._get_padding_widths(options))
if options["vrules"] in (FRAME, ALL):
title_width += 2
else:
@@ -1065,8 +1095,8 @@ class PrettyTable(object):
table_width = self._compute_table_width(options)
if table_width < min_width:
# Grow widths in proportion
- scale = 1.0*min_width / table_width
- widths = [int(math.ceil(w*scale)) for w in widths]
+ scale = 1.0 * min_width / table_width
+ widths = [int(math.ceil(w * scale)) for w in widths]
self._widths = widths
def _get_padding_widths(self, options):
@@ -1097,7 +1127,7 @@ class PrettyTable(object):
if options["sortby"]:
sortindex = self._field_names.index(options["sortby"])
# Decorate
- rows = [[row[sortindex]]+row for row in rows]
+ rows = [[row[sortindex]] + row for row in rows]
# Sort
rows.sort(reverse=options["reversesort"], key=options["sort_key"])
# Undecorate
@@ -1197,12 +1227,12 @@ class PrettyTable(object):
bits = [options["horizontal_char"]]
# For tables with no data or fieldnames
if not self._field_names:
- bits.append(options["junction_char"])
- return "".join(bits)
+ bits.append(options["junction_char"])
+ return "".join(bits)
for field, width in zip(self._field_names, self._widths):
if options["fields"] and field not in options["fields"]:
continue
- bits.append((width+lpad+rpad)*options["horizontal_char"])
+ bits.append((width + lpad + rpad) * options["horizontal_char"])
if options['vrules'] == ALL:
bits.append(options["junction_char"])
else:
@@ -1226,8 +1256,8 @@ class PrettyTable(object):
bits = []
endpoint = options["vertical_char"] if options["vrules"] in (ALL, FRAME) else " "
bits.append(endpoint)
- title = " "*lpad + title + " "*rpad
- bits.append(self._justify(title, len(self._hrule)-2, "c"))
+ title = " " * lpad + title + " " * rpad
+ bits.append(self._justify(title, len(self._hrule) - 2, "c"))
bits.append(endpoint)
lines.append("".join(bits))
return "\n".join(lines)
@@ -1281,7 +1311,7 @@ class PrettyTable(object):
def _stringify_row(self, row, options):
- for index, field, value, width, in zip(range(0,len(row)), self._field_names, row, self._widths):
+ for index, field, value, width, in zip(range(0, len(row)), self._field_names, row, self._widths):
# Enforce max widths
lines = value.split("\n")
new_lines = []
@@ -1342,9 +1372,9 @@ class PrettyTable(object):
bits[y].pop()
bits[y].append(options["vertical_char"])
- if options["border"] and options["hrules"]== ALL:
- bits[row_height-1].append("\n")
- bits[row_height-1].append(self._hrule)
+ if options["border"] and options["hrules"] == ALL:
+ bits[row_height - 1].append("\n")
+ bits[row_height - 1].append(self._hrule)
for y in range(0, row_height):
bits[y] = "".join(bits[y])
@@ -1495,7 +1525,9 @@ class PrettyTable(object):
for field in self._field_names:
if options["fields"] and field not in options["fields"]:
continue
- lines.append(" <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (lpad, rpad, escape(field).replace("\n", linebreak)))
+ lines.append(
+ " <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (
+ lpad, rpad, escape(field).replace("\n", linebreak)))
lines.append(" </tr>")
# Data
@@ -1504,19 +1536,22 @@ class PrettyTable(object):
aligns = []
valigns = []
for field in self._field_names:
- aligns.append({ "l" : "left", "r" : "right", "c" : "center" }[self._align[field]])
- valigns.append({"t" : "top", "m" : "middle", "b" : "bottom"}[self._valign[field]])
+ aligns.append({"l": "left", "r": "right", "c": "center"}[self._align[field]])
+ valigns.append({"t": "top", "m": "middle", "b": "bottom"}[self._valign[field]])
for row in formatted_rows:
lines.append(" <tr>")
for field, datum, align, valign in zip(self._field_names, row, aligns, valigns):
if options["fields"] and field not in options["fields"]:
continue
- lines.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: %s; vertical-align: %s\">%s</td>" % (lpad, rpad, align, valign, escape(datum).replace("\n", linebreak)))
+ lines.append(
+ " <td style=\"padding-left: %dem; padding-right: %dem; text-align: %s; vertical-align: %s\">%s</td>" % (
+ lpad, rpad, align, valign, escape(datum).replace("\n", linebreak)))
lines.append(" </tr>")
lines.append("</table>")
return self._unicode("\n").join(lines)
+
##############################
# UNICODE WIDTH FUNCTIONS #
##############################
@@ -1554,19 +1589,19 @@ def _char_block_width(char):
# Take a guess
return 1
-def _str_block_width(val):
+def _str_block_width(val):
return sum(itermap(_char_block_width, itermap(ord, _re.sub("", val))))
+
##############################
# TABLE FACTORIES #
##############################
-def from_csv(fp, field_names = None, **kwargs):
-
+def from_csv(fp, field_names=None, **kwargs):
fmtparams = {}
for param in ["delimiter", "doublequote", "escapechar", "lineterminator",
- "quotechar", "quoting", "skipinitialspace", "strict"]:
+ "quotechar", "quoting", "skipinitialspace", "strict"]:
if param in kwargs:
fmtparams[param] = kwargs.pop(param)
if fmtparams:
@@ -1590,8 +1625,8 @@ def from_csv(fp, field_names = None, **kwargs):
return table
-def from_db_cursor(cursor, **kwargs):
+def from_db_cursor(cursor, **kwargs):
if cursor.description:
table = PrettyTable(**kwargs)
table.field_names = [col[0] for col in cursor.description]
@@ -1599,8 +1634,8 @@ def from_db_cursor(cursor, **kwargs):
table.add_row(row)
return table
-class TableHandler(HTMLParser):
+class TableHandler(HTMLParser):
def __init__(self, **kwargs):
HTMLParser.__init__(self)
self.kwargs = kwargs
@@ -1613,7 +1648,7 @@ class TableHandler(HTMLParser):
self.is_last_row_header = False
self.colspan = 0
- def handle_starttag(self,tag, attrs):
+ def handle_starttag(self, tag, attrs):
self.active = tag
if tag == "th":
self.is_last_row_header = True
@@ -1622,7 +1657,7 @@ class TableHandler(HTMLParser):
self.colspan = int(value)
- def handle_endtag(self,tag):
+ def handle_endtag(self, tag):
if tag in ["th", "td"]:
stripped_content = self.last_content.strip()
self.last_row.append(stripped_content)
@@ -1656,7 +1691,7 @@ class TableHandler(HTMLParser):
for row in self.rows:
if len(row[0]) < self.max_row_width:
appends = self.max_row_width - len(row[0])
- for i in range(1,appends):
+ for i in range(1, appends):
row[0].append("-")
if row[1] == True:
@@ -1671,10 +1706,11 @@ class TableHandler(HTMLParser):
iterates over the row and make each field unique
"""
for i in range(0, len(fields)):
- for j in range(i+1, len(fields)):
+ for j in range(i + 1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'"
+
def from_html(html_code, **kwargs):
"""
Generates a list of PrettyTables from a string of HTML code. Each <table> in
@@ -1685,6 +1721,7 @@ def from_html(html_code, **kwargs):
parser.feed(html_code)
return parser.tables
+
def from_html_one(html_code, **kwargs):
"""
Generates a PrettyTables from a string of HTML code which contains only a
@@ -1698,12 +1735,12 @@ def from_html_one(html_code, **kwargs):
raise Exception("More than one <table> in provided HTML code! Use from_html instead.")
return tables[0]
+
##############################
# MAIN (TEST FUNCTION) #
##############################
def main():
-
print("Generated using setters:")
x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.title = "Australian capital cities"
@@ -1711,7 +1748,7 @@ def main():
x.reversesort = True
x.int_format["Area"] = "04"
x.float_format = "6.1"
- x.align["City name"] = "l" # Left align city names
+ x.align["City name"] = "l" # Left align city names
x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
@@ -1726,16 +1763,16 @@ def main():
print("Generated using constructor arguments:")
y = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"],
- title = "Australian capital cities",
- sortby = "Population",
- reversesort = True,
- int_format = "04",
- float_format = "6.1",
- max_width = 12,
- min_width = 4,
- align = "c",
- valign = "t")
- y.align["City name"] = "l" # Left align city names
+ title="Australian capital cities",
+ sortby="Population",
+ reversesort=True,
+ int_format="04",
+ float_format="6.1",
+ max_width=12,
+ min_width=4,
+ align="c",
+ valign="t")
+ y.align["City name"] = "l" # Left align city names
y.add_row(["Adelaide", 1295, 1158259, 600.5])
y.add_row(["Brisbane", 5905, 1857594, 1146.4])
y.add_row(["Darwin", 112, 120900, 1714.7])
@@ -1745,5 +1782,6 @@ def main():
y.add_row(["Perth", 5386, 1554769, 869.4])
print(y)
+
if __name__ == "__main__":
main()
diff --git a/prettytable_test.py b/prettytable_test.py
index ce03780..1552505 100644
--- a/prettytable_test.py
+++ b/prettytable_test.py
@@ -4,9 +4,11 @@
from prettytable import *
import sys
+
py3k = sys.version_info[0] >= 3
try:
import sqlite3
+
_have_sqlite = True
except ImportError:
_have_sqlite = False
@@ -17,17 +19,16 @@ else:
from math import pi, e, sqrt
import unittest
-class BuildEquivelanceTest(unittest.TestCase):
+class BuildEquivelanceTest(unittest.TestCase):
"""Make sure that building a table row-by-row and column-by-column yield the same results"""
def setUp(self):
-
# Row by row...
self.row = PrettyTable()
self.row.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
- self.row.add_row(["Adelaide",1295, 1158259, 600.5])
- self.row.add_row(["Brisbane",5905, 1857594, 1146.4])
+ self.row.add_row(["Adelaide", 1295, 1158259, 600.5])
+ self.row.add_row(["Brisbane", 5905, 1857594, 1146.4])
self.row.add_row(["Darwin", 112, 120900, 1714.7])
self.row.add_row(["Hobart", 1357, 205556, 619.5])
self.row.add_row(["Sydney", 2058, 4336374, 1214.8])
@@ -36,41 +37,38 @@ class BuildEquivelanceTest(unittest.TestCase):
# Column by column...
self.col = PrettyTable()
- self.col.add_column("City name",["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"])
+ self.col.add_column("City name", ["Adelaide", "Brisbane", "Darwin", "Hobart", "Sydney", "Melbourne", "Perth"])
self.col.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
self.col.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769])
- self.col.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4])
+ self.col.add_column("Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4])
# A mix of both!
self.mix = PrettyTable()
self.mix.field_names = ["City name", "Area"]
- self.mix.add_row(["Adelaide",1295])
- self.mix.add_row(["Brisbane",5905])
+ self.mix.add_row(["Adelaide", 1295])
+ self.mix.add_row(["Brisbane", 5905])
self.mix.add_row(["Darwin", 112])
self.mix.add_row(["Hobart", 1357])
self.mix.add_row(["Sydney", 2058])
self.mix.add_row(["Melbourne", 1566])
self.mix.add_row(["Perth", 5386])
self.mix.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769])
- self.mix.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4])
+ self.mix.add_column("Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4])
def testRowColEquivalenceASCII(self):
-
self.assertEqual(self.row.get_string(), self.col.get_string())
def testRowMixEquivalenceASCII(self):
-
self.assertEqual(self.row.get_string(), self.mix.get_string())
def testRowColEquivalenceHTML(self):
-
self.assertEqual(self.row.get_html_string(), self.col.get_html_string())
def testRowMixEquivalenceHTML(self):
-
self.assertEqual(self.row.get_html_string(), self.mix.get_html_string())
-#class FieldnamelessTableTest(unittest.TestCase):
+
+# class FieldnamelessTableTest(unittest.TestCase):
#
# """Make sure that building and stringing a table with no fieldnames works fine"""
#
@@ -95,22 +93,20 @@ class BuildEquivelanceTest(unittest.TestCase):
# self.x.get_string()
class CityDataTest(unittest.TestCase):
-
"""Just build the Australian capital city data example table."""
def setUp(self):
-
self.x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
- self.x.add_row(["Adelaide",1295, 1158259, 600.5])
- self.x.add_row(["Brisbane",5905, 1857594, 1146.4])
+ self.x.add_row(["Adelaide", 1295, 1158259, 600.5])
+ self.x.add_row(["Brisbane", 5905, 1857594, 1146.4])
self.x.add_row(["Darwin", 112, 120900, 1714.7])
self.x.add_row(["Hobart", 1357, 205556, 619.5])
self.x.add_row(["Sydney", 2058, 4336374, 1214.8])
self.x.add_row(["Melbourne", 1566, 3806092, 646.9])
self.x.add_row(["Perth", 5386, 1554769, 869.4])
-class OptionOverrideTests(CityDataTest):
+class OptionOverrideTests(CityDataTest):
"""Make sure all options are properly overwritten by get_string."""
def testBorder(self):
@@ -129,13 +125,12 @@ class OptionOverrideTests(CityDataTest):
self.assertTrue(default != override)
def testHrulesNone(self):
-
default = self.x.get_string()
override = self.x.get_string(hrules=NONE)
self.assertTrue(default != override)
-class OptionAttributeTests(CityDataTest):
+class OptionAttributeTests(CityDataTest):
"""Make sure all options which have an attribute interface work as they should.
Also make sure option settings are copied correctly when a table is cloned by
slicing."""
@@ -160,7 +155,7 @@ class OptionAttributeTests(CityDataTest):
self.x.horizontal_char = "~"
self.x.junction_char = "*"
self.x.format = True
- self.x.attributes = {"class" : "prettytable"}
+ self.x.attributes = {"class": "prettytable"}
assert self.x.get_string() == self.x[:].get_string()
def testSetForOneColumn(self):
@@ -170,12 +165,11 @@ class OptionAttributeTests(CityDataTest):
self.x.float_format["Area"] = "2.2"
assert self.x.get_string() == self.x[:].get_string()
-class BasicTests(CityDataTest):
+class BasicTests(CityDataTest):
"""Some very basic tests."""
def testNoBlankLines(self):
-
"""No table should ever have blank lines in it."""
string = self.x.get_string()
@@ -183,57 +177,56 @@ class BasicTests(CityDataTest):
self.assertTrue("" not in lines)
def testAllLengthsEqual(self):
-
"""All lines in a table should be of the same length."""
string = self.x.get_string()
lines = string.split("\n")
lengths = [len(line) for line in lines]
lengths = set(lengths)
- self.assertEqual(len(lengths),1)
+ self.assertEqual(len(lengths), 1)
-class TitleBasicTests(BasicTests):
+class TitleBasicTests(BasicTests):
"""Run the basic tests with a title"""
def setUp(self):
BasicTests.setUp(self)
self.x.title = "My table"
-class NoBorderBasicTests(BasicTests):
+class NoBorderBasicTests(BasicTests):
"""Run the basic tests with border = False"""
def setUp(self):
BasicTests.setUp(self)
self.x.border = False
-class NoHeaderBasicTests(BasicTests):
+class NoHeaderBasicTests(BasicTests):
"""Run the basic tests with header = False"""
def setUp(self):
BasicTests.setUp(self)
self.x.header = False
-class HrulesNoneBasicTests(BasicTests):
+class HrulesNoneBasicTests(BasicTests):
"""Run the basic tests with hrules = NONE"""
def setUp(self):
BasicTests.setUp(self)
self.x.hrules = NONE
-class HrulesAllBasicTests(BasicTests):
+class HrulesAllBasicTests(BasicTests):
"""Run the basic tests with hrules = ALL"""
def setUp(self):
BasicTests.setUp(self)
self.x.hrules = ALL
-class EmptyTableTests(CityDataTest):
+class EmptyTableTests(CityDataTest):
"""Make sure the print_empty option works"""
def setUp(self):
@@ -252,16 +245,16 @@ class EmptyTableTests(CityDataTest):
def testInteractionWithBorder(self):
assert self.y.get_string(border=False, print_empty=True) == ""
-class PresetBasicTests(BasicTests):
+class PresetBasicTests(BasicTests):
"""Run the basic tests after using set_style"""
def setUp(self):
BasicTests.setUp(self)
self.x.set_style(MSWORD_FRIENDLY)
-class SlicingTests(CityDataTest):
+class SlicingTests(CityDataTest):
def setUp(self):
CityDataTest.setUp(self)
@@ -287,8 +280,8 @@ class SlicingTests(CityDataTest):
assert "Melbourne" in string
assert "Perth" in string
-class SortingTests(CityDataTest):
+class SortingTests(CityDataTest):
def setUp(self):
CityDataTest.setUp(self)
@@ -307,7 +300,7 @@ class SortingTests(CityDataTest):
forward = self.x.get_string()
self.x.reversesort = True
backward = self.x.get_string()
- forward_lines = forward.split("\n")[2:] # Discard header lines
+ forward_lines = forward.split("\n")[2:] # Discard header lines
backward_lines = backward.split("\n")[2:]
backward_lines.reverse()
assert forward_lines == backward_lines
@@ -317,6 +310,7 @@ class SortingTests(CityDataTest):
def key(vals):
vals[0] = len(vals[0])
return vals
+
self.x.sortby = "City name"
self.x.sort_key = key
assert self.x.get_string().strip() == """+-----------+------+------------+-----------------+
@@ -344,24 +338,24 @@ class SortingTests(CityDataTest):
assert "10" not in oldstyle
assert "20" in oldstyle
-class IntegerFormatBasicTests(BasicTests):
+class IntegerFormatBasicTests(BasicTests):
"""Run the basic tests after setting an integer format string"""
def setUp(self):
BasicTests.setUp(self)
self.x.int_format = "04"
-class FloatFormatBasicTests(BasicTests):
+class FloatFormatBasicTests(BasicTests):
"""Run the basic tests after setting a float format string"""
def setUp(self):
BasicTests.setUp(self)
self.x.float_format = "6.2f"
-class FloatFormatTests(unittest.TestCase):
+class FloatFormatTests(unittest.TestCase):
def setUp(self):
self.x = PrettyTable(["Constant", "Value"])
self.x.add_row(["Pi", pi])
@@ -391,6 +385,7 @@ class FloatFormatTests(unittest.TestCase):
assert "002.72" in string
assert "001.41" in string
+
class BreakLineTests(unittest.TestCase):
def testAsciiBreakLine(self):
t = PrettyTable(['Field 1', 'Field 2'])
@@ -465,8 +460,8 @@ class BreakLineTests(unittest.TestCase):
</table>
""".strip()
-class HtmlOutputTests(unittest.TestCase):
+class HtmlOutputTests(unittest.TestCase):
def testHtmlOutput(self):
t = PrettyTable(['Field 1', 'Field 2', 'Field 3'])
t.add_row(['value 1', 'value2', 'value3'])
@@ -529,10 +524,9 @@ class HtmlOutputTests(unittest.TestCase):
</table>
""".strip()
-class CsvConstructorTest(BasicTests):
+class CsvConstructorTest(BasicTests):
def setUp(self):
-
csv_string = """City name, Area , Population , Annual Rainfall
Sydney, 2058 , 4336374 , 1214.8
Melbourne, 1566 , 3806092 , 646.9
@@ -544,9 +538,9 @@ class CsvConstructorTest(BasicTests):
csv_fp = StringIO.StringIO(csv_string)
self.x = from_csv(csv_fp)
+
if _have_sqlite:
class DatabaseConstructorTest(BasicTests):
-
def setUp(self):
self.conn = sqlite3.connect(":memory:")
self.cur = self.conn.cursor()
@@ -565,8 +559,8 @@ if _have_sqlite:
self.cur.execute("INSERT INTO cities VALUES (\"Adelaide\", 1295, 1158259, 600.5)")
assert from_db_cursor(self.cur) is None
-class HtmlConstructorTest(CityDataTest):
+class HtmlConstructorTest(CityDataTest):
def testHtmlAndBack(self):
html_string = self.x.get_html_string()
new_table = from_html(html_string)[0]
@@ -582,16 +576,15 @@ class HtmlConstructorTest(CityDataTest):
html_string += self.x.get_html_string()
self.assertRaises(Exception, from_html_one, html_string)
-class PrintEnglishTest(CityDataTest):
+class PrintEnglishTest(CityDataTest):
def testPrint(self):
print()
print(self.x)
-class PrintJapanestTest(unittest.TestCase):
+class PrintJapanestTest(unittest.TestCase):
def setUp(self):
-
self.x = PrettyTable(["Kanji", "Hiragana", "English"])
self.x.add_row(["神戸", "こうべ", "Kobe"])
self.x.add_row(["京都", "きょうと", "Kyoto"])
@@ -606,5 +599,6 @@ class PrintJapanestTest(unittest.TestCase):
print()
print(self.x)
+
if __name__ == "__main__":
unittest.main()
diff --git a/setup.py b/setup.py
index 20a2322..37061df 100644
--- a/setup.py
+++ b/setup.py
@@ -21,5 +21,5 @@ setup(
author_email='luke@maurits.id.au',
url='http://code.google.com/p/prettytable',
py_modules=['prettytable'],
- test_suite = "prettytable_test"
+ test_suite="prettytable_test"
)