Skip to content

Commit

Permalink
Update of the add_row api to satisfy #7
Browse files Browse the repository at this point in the history
  • Loading branch information
root-11 committed Oct 30, 2020
1 parent fbb0f17 commit e09c4ee
Show file tree
Hide file tree
Showing 4 changed files with 188 additions and 9 deletions.
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,65 @@ table5_from_json = Table.from_json(table5_json)
assert table5 == table5_from_json
```
### How do I add data again?

Here's a couple of examples:

```
from table import Table
from itertools import count
t = Table()
t.add_column('row', int)
t.add_column('A', int)
t.add_column('B', int)
t.add_column('C', int)
test_number = count(1)
```

The following examples are all valid and append the row (1,2,3) to the table.

```
t.add_row(1, 1, 2, 3)
t.add_row([2, 1, 2, 3])
t.add_row((3, 1, 2, 3))
t.add_row(*(4, 1, 2, 3))
t.add_row(row=5, A=1, B=2, C=3)
t.add_row(**{'row': 6, 'A': 1, 'B': 2, 'C': 3})
```

The following examples add two rows to the table

```
t.add_row((7, 1, 2, 3), (8, 4, 5, 6))
t.add_row([9, 1, 2, 3], [10, 4, 5, 6])
t.add_row({'row': 11, 'A': 1, 'B': 2, 'C': 3},
{'row': 12, 'A': 4, 'B': 5, 'C': 6}) # two (or more) dicts as args.
t.add_row(*[{'row': 13, 'A': 1, 'B': 2, 'C': 3},
{'row': 14, 'A': 1, 'B': 2, 'C': 3}]) # list of dicts.
t.show()
# +=====+=====+=====+=====+
# | row | A | B | C |
# | int | int | int | int |
# |False|False|False|False|
# +-----+-----+-----+-----+
# | 1| 1| 2| 3|
# | 2| 1| 2| 3|
# | 3| 1| 2| 3|
# | 4| 1| 2| 3|
# | 5| 1| 2| 3|
# | 6| 1| 2| 3|
# | 7| 1| 2| 3|
# | 8| 4| 5| 6|
# | 9| 1| 2| 3|
# | 10| 4| 5| 6|
# | 11| 1| 2| 3|
# | 12| 4| 5| 6|
# | 13| 1| 2| 3|
# | 14| 1| 2| 3|
# +=====+=====+=====+=====+
```

### Okay, great. How do I load data?

Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
tablite
"""
build_tag = "7c956f59d30ae1bd659383650e4edccf085a32c7178c9a88d29ab1a476fabb76"
build_tag = "f783c9b18debe9f811aa55f878ca176342ecea6d87be8e8d25ecdf51e7db9806"
from setuptools import setup
from pathlib import Path

Expand All @@ -28,7 +28,7 @@

setup(
name="tablite",
version="2020.10.28.59904",
version="2020.10.30.46577",
url="https://github.com/root-11/tablite",
license="MIT",
author="Bjorn Madsen",
Expand Down
83 changes: 76 additions & 7 deletions table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,13 +1439,82 @@ def add_column(self, header, datatype, allow_empty=False, data=None):
else:
self.columns[header] = StoredColumn(header, datatype, allow_empty, data=data)

def add_row(self, values):
if not isinstance(values, tuple):
raise TypeError(f"expected tuple, got {type(values)}")
if len(values) != len(self.columns):
raise ValueError(f"expected {len(self.columns)} values not {len(values)}: {values}")
for value, col in zip(values, self.columns.values()):
col.append(value)
def add_row(self, *args, **kwargs):
""" Adds row(s) to the table.
:param args: see below
:param kwargs: see below
:return: None
Example:
t = Table()
t.add_column('A', int)
t.add_column('B', int)
t.add_column('C', int)
The following examples are all valid and append the row (1,2,3) to the table.
t.add_row(1,2,3)
t.add_row([1,2,3])
t.add_row((1,2,3))
t.add_row(*(1,2,3))
t.add_row(A=1, B=2, C=3)
t.add_row(**{'A':1, 'B':2, 'C':3})
The following examples add two rows to the table
t.add_row((1,2,3), (4,5,6))
t.add_row([1,2,3], [4,5,6])
t.add_row({'A':1, 'B':2, 'C':3}, {'A':4, 'B':5, 'C':6}) # two (or more) dicts as args.
t.add_row([{'A':1, 'B':2, 'C':3}, {'A':1, 'B':2, 'C':3}]) # list of dicts.
"""
if args:
if not any(isinstance(i, (list, tuple, dict)) for i in args):
if len(args) == len(self.columns):
args = (args, )
elif len(args) < len(self.columns):
raise TypeError(f"{args} doesn't match the number of columns. Are values missing?")
elif len(args) > len(self.columns):
raise TypeError(f"{args} doesn't match the number of columns. Too many values?")
else:
raise TypeError(f"{args} doesn't match the format of the table.")

for arg in args:
if len(arg) != len(self.columns):
raise ValueError(f"expected {len(self.columns)} columns, not {len(arg)}: {arg}")

if isinstance(arg, (list, tuple)):
for value, col in zip(arg, self.columns.values()):
col.append(value)

elif isinstance(arg, dict):
for k, value in arg.items():
col = self.columns.get(k, None)
if col is None:
raise ValueError(f"column {k} unknown: {list(self.columns)}")
assert isinstance(col, (Column, StoredColumn))
col.append(value)
else:
raise TypeError(f"no handler for {type(arg)}s: {arg}")

if kwargs:
if len(kwargs) < len(self.columns):
missing = [k for k in kwargs if k not in self.columns]
raise ValueError(f"expected {len(self.columns)} columns, not {len(kwargs)}: Missing columns: {missing}")
elif len(kwargs) > len(self.columns):
excess = [k for k in kwargs if k not in self.columns]
raise ValueError(f"expected {len(self.columns)} columns, not {len(kwargs)}: Excess columns: {excess}")
else:
pass # looks alright.

for k, value in kwargs.items():
col = self.columns.get(k, None)
if col is None:
raise ValueError(f"column {k} unknown: {list(self.columns)}")
assert isinstance(col, (Column, StoredColumn))
col.append(value)
return

def __contains__(self, item):
return item in self.columns
Expand Down
51 changes: 51 additions & 0 deletions tests/table_tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from table import *
from datetime import date, time, datetime
from itertools import count
import zlib


Expand Down Expand Up @@ -200,6 +201,56 @@ def f2(b, c, d):
assert table5 == table5_from_json


def test_add_rows():
""" Example from docstring. """
t = Table()
t.add_column('test', int)
t.add_column('A', int)
t.add_column('B', int)
t.add_column('C', int)
test_number = count(1)

# The following examples are all valid and append the row (1,2,3) to the table.

t.add_row(next(test_number), 1, 2, 3)
t.add_row([next(test_number), 1, 2, 3])
t.add_row((next(test_number), 1, 2, 3))
t.add_row(*(next(test_number), 1, 2, 3))
t.add_row(test=next(test_number), A=1, B=2, C=3)
t.add_row(**{'test': next(test_number), 'A': 1, 'B': 2, 'C': 3})

# The following examples add two rows to the table

t.add_row((next(test_number), 1, 2, 3), (next(test_number), 4, 5, 6))
t.add_row([next(test_number), 1, 2, 3], [next(test_number), 4, 5, 6])
t.add_row({'test': next(test_number), 'A': 1, 'B': 2, 'C': 3},
{'test': next(test_number), 'A': 4, 'B': 5, 'C': 6}) # two (or more) dicts as args.
t.add_row(*[{'test': next(test_number), 'A': 1, 'B': 2, 'C': 3},
{'test': next(test_number), 'A': 1, 'B': 2, 'C': 3}]) # list of dicts.
t.show() # expects:
# +=====+=====+=====+=====+
# | test| A | B | C |
# | int | int | int | int |
# |False|False|False|False|
# +-----+-----+-----+-----+
# | 1| 1| 2| 3|
# | 2| 1| 2| 3|
# | 3| 1| 2| 3|
# | 4| 1| 2| 3|
# | 5| 1| 2| 3|
# | 6| 1| 2| 3|
# | 7| 1| 2| 3|
# | 8| 4| 5| 6|
# | 9| 1| 2| 3|
# | 10| 4| 5| 6|
# | 11| 1| 2| 3|
# | 12| 4| 5| 6|
# | 13| 1| 2| 3|
# | 14| 1| 2| 3|
# +=====+=====+=====+=====+
assert next(test_number) == 14 + 1


def test_lookup_functions(): # doing lookups is supported by indexing:
table6 = Table()
table6.add_column('A', str, data=['Alice', 'Bob', 'Bob', 'Ben', 'Charlie', 'Ben', 'Albert'])
Expand Down

0 comments on commit e09c4ee

Please sign in to comment.