Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
Copyright (c) 2010, Marty Alchin
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission.
Copyright (c) 2010, Marty Alchin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6 changes: 3 additions & 3 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
include LICENSE.txt
include contents.csv
recursive-include tests *.py
include LICENSE.txt
include contents.csv
recursive-include tests *.py
34 changes: 17 additions & 17 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
from distutils.core import setup
setup(name='Sheets',
version='0.6',
author='Marty Alchin',
author_email='marty@martyalchin.com',
url='https://github.com/gulopine/sheets/',
packages=['sheets'],
license='BSD',
description='A declarative class framework for working with CSV files',
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Programming Language :: Python :: 3.1',
]
from distutils.core import setup

setup(name='Sheets',
version='0.6',
author='Marty Alchin',
author_email='marty@martyalchin.com',
url='https://github.com/gulopine/sheets/',
packages=['sheets'],
license='BSD',
description='A declarative class framework for working with CSV files',
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Programming Language :: Python :: 3.1',
]
)
6 changes: 3 additions & 3 deletions sheets/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from sheets.base import *
from sheets.options import *
from sheets.columns import *
from sheets.base import *
from sheets.options import *
from sheets.columns import *
230 changes: 113 additions & 117 deletions sheets/base.py
Original file line number Diff line number Diff line change
@@ -1,117 +1,113 @@
import csv
from collections import OrderedDict

from sheets import options

__all__ = ['Row', 'Reader', 'Writer']

class RowMeta(type):
def __init__(cls, name, bases, attrs):
if 'Dialect' in attrs:
# Filter out Python's own additions to the namespace
items = attrs.pop('Dialect').__dict__.items()
items = dict((k, v) for (k, v) in items if not k.startswith('__'))
else:
# No options were explicitly defined
items = {}
cls._dialect = options.Dialect(**items)

for key, attr in attrs.items():
if hasattr(attr, 'attach_to_class'):
attr.attach_to_class(cls, key, cls._dialect)

@classmethod
def __prepare__(cls, name, bases):
return OrderedDict()


class Row(metaclass=RowMeta):
# Not yet written about

def __init__(self, *args, **kwargs):
column_names = [column.name for column in self._dialect.columns]

# First, make sure the arguments make sense
if len(args) > len(column_names):
msg = "__init__() takes at most %d arguments (%d given)"
raise TypeError(msg % (len(column_names), len(args)))

for name in kwargs:
if name not in column_names:
raise TypeError("Got unknown keyword argument '%s'" % name)

for i, name in enumerate(column_names[:len(args)]):
if name in kwargs:
msg = "__init__() got multiple values for keyword argument '%s'"
raise TypeError(msg % name)
kwargs[name] = args[i]

# Now populate the actual values on the object
for column in self._dialect.columns:
try:
value = column.to_python(kwargs[column.name])
except KeyError:
# No value was provided
value = None
setattr(self, column.name, value)

errors = ()

def is_valid(self):
valid = True
self.errors = []
for column in self._dialect.columns:
value = getattr(self, column.name)
try:
column.validate(value)
except ValueError as e:
self.errors.append(e)
valid = False
return valid

@classmethod
def reader(cls, file):
return Reader(cls, file)

@classmethod
def writer(cls, file):
return Writer(cls, file)


class Reader:
def __init__(self, row_cls, file):
self.row_cls = row_cls
self.csv_reader = csv.reader(file, **row_cls._dialect.csv_dialect)
self.skip_header_row = row_cls._dialect.has_header_row

def __iter__(self):
return self

def __next__(self):
# Skip the first row if it's a header
if self.skip_header_row:
self.csv_reader.__next__()
self.skip_header_row = False

return self.row_cls(*self.csv_reader.__next__())


class Writer:
def __init__(self, row_cls, file):
self.columns = row_cls._dialect.columns
self._writer = csv.writer(file, row_cls._dialect.csv_dialect)
self.needs_header_row = row_cls._dialect.has_header_row

def writerow(self, row):
if self.needs_header_row:
values = [column.title.title() for column in self.columns]
self._writer.writerow(values)
self.needs_header_row = False
values = [getattr(row, column.name) for column in self.columns]
self._writer.writerow(values)

def writerows(self, rows):
for row in rows:
self.writerow(row)


import csv

from sheets import options

__all__ = ['Row', 'Reader', 'Writer']


class RowMeta(type):
def __init__(cls, name, bases, attrs):
if 'Dialect' in attrs:
# Filter out Python's own additions to the namespace
items = attrs.pop('Dialect').__dict__.items()
items = dict((k, v) for (k, v) in items if not k.startswith('__'))
else:
# No options were explicitly defined
items = {}
cls._dialect = options.Dialect(**items)

for key, attr in attrs.items():
if hasattr(attr, 'attach_to_class'):
attr.attach_to_class(cls, key, cls._dialect)


class Row(object):
__metaclass__ = RowMeta
# Not yet written about

def __init__(self, *args, **kwargs):
column_names = [column.name for column in self._dialect.columns]

# First, make sure the arguments make sense
if len(args) > len(column_names):
msg = "__init__() takes at most %d arguments (%d given)"
raise TypeError(msg % (len(column_names), len(args)))

for name in kwargs:
if name not in column_names:
raise TypeError("Got unknown keyword argument '%s'" % name)

for i, name in enumerate(column_names[:len(args)]):
if name in kwargs:
msg = ("__init__() got multiple values for keyword argument "
"'%s'")
raise TypeError(msg % name)
kwargs[name] = args[i]

# Now populate the actual values on the object
for column in self._dialect.columns:
try:
value = column.to_python(kwargs[column.name])
except KeyError:
# No value was provided
value = None
setattr(self, column.name, value)

errors = ()

def is_valid(self):
valid = True
self.errors = []
for column in self._dialect.columns:
value = getattr(self, column.name)
try:
column.validate(value)
except ValueError as e:
self.errors.append(e)
valid = False
return valid

@classmethod
def reader(cls, file):
return Reader(cls, file)

@classmethod
def writer(cls, file):
return Writer(cls, file)


class Reader(object):
def __init__(self, row_cls, file):
self.row_cls = row_cls
self.csv_reader = csv.reader(file, **row_cls._dialect.csv_dialect)
self.skip_header_row = row_cls._dialect.has_header_row

def __iter__(self):
return self

def __next__(self):
# Skip the first row if it's a header
if self.skip_header_row:
self.csv_reader.__next__()
self.skip_header_row = False

return self.row_cls(*self.csv_reader.__next__())


class Writer(object):
def __init__(self, row_cls, file):
self.columns = row_cls._dialect.columns
self._writer = csv.writer(file, row_cls._dialect.csv_dialect)
self.needs_header_row = row_cls._dialect.has_header_row

def writerow(self, row):
if self.needs_header_row:
values = [column.title.title() for column in self.columns]
self._writer.writerow(values)
self.needs_header_row = False
values = [getattr(row, column.name) for column in self.columns]
self._writer.writerow(values)

def writerows(self, rows):
for row in rows:
self.writerow(row)
Loading