Skip to content
This repository has been archived by the owner on Apr 10, 2023. It is now read-only.

Module renames #52

Merged
merged 1 commit into from
Jan 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 3 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: help clean venv install install-plain install-dev install-all lint sort-imports \
.PHONY: help clean install install-plain install-dev install-all lint sort-imports \
test test-plain docs docs-clean docs-open docs-test dist release

PYTHON := python3
Expand All @@ -9,11 +9,8 @@ help: ## Show this message and exit.
/^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-13s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)

clean: docs-clean ## Remove all build artifacts.
rm -rf build dist wheels venv *.egg-info
find . \( -name *.pyc -o -name *.pyo -o -name __pycache__ \) -exec rm -rf {} +

venv: ## Create virtualenv.
virtualenv --python=$(PYTHON) venv
rm -rf build dist wheels
find . \( -name *.pyc -o -name *.pyo -o -name __pycache__ -o -name *.egg-info \) -exec rm -rf {} +

install: ## Install package and all features.
$(VIRTUAL_ENV)/bin/pip install -e ".[toml,yaml]"
Expand Down
4 changes: 2 additions & 2 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ API
.. toctree::

model
field
error
fields
exceptions
validate
8 changes: 5 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@

# General configuration
default_role = 'obj'
doctest_default_flags = (doctest.DONT_ACCEPT_TRUE_FOR_1
| doctest.ELLIPSIS
| doctest.NORMALIZE_WHITESPACE)
doctest_default_flags = (
doctest.DONT_ACCEPT_TRUE_FOR_1
| doctest.ELLIPSIS
| doctest.NORMALIZE_WHITESPACE
)
doctest_global_setup = 'from serde import *'
extensions = [
'sphinx.ext.autodoc',
Expand Down
6 changes: 0 additions & 6 deletions docs/error.rst

This file was deleted.

6 changes: 6 additions & 0 deletions docs/exceptions.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Exceptions
==========

.. automodule:: serde.exceptions
:members:
:show-inheritance:
6 changes: 0 additions & 6 deletions docs/field.rst

This file was deleted.

6 changes: 6 additions & 0 deletions docs/fields.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Fields
======

.. automodule:: serde.fields
:members:
:show-inheritance:
16 changes: 8 additions & 8 deletions src/serde/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
serializing, deserializing, and validating data structures in Python.

Objects are defined by subclassing `~serde.model.Model` and assigning
`~serde.field.Field` attributes on the Model. In the following example `User` is
the subclassed `~serde.model.Model` with two fields `name` and `age`. The
`~serde.field.Str` and `~serde.field.Int` classes handle serialization,
`~serde.fields.Field` attributes on the Model. In the following example `User`
is the subclassed `~serde.model.Model` with two fields `name` and `age`. The
`~serde.fields.Str` and `~serde.fields.Int` classes handle serialization,
deserialization, and validation for these attributes.

::

>>> from serde import Model, field
>>> from serde import Model, fields

>>> class User(Model):
... name = field.Str(rename='username')
... age = field.Optional(field.Int)
... name = fields.Str(rename='username')
... age = fields.Optional(fields.Int)

Models are validated when they are instantiated and after they are deserialized.

Expand Down Expand Up @@ -50,13 +50,13 @@
Other supported data formats including `JSON <serde.model.Model.to_json()>`,
`TOML <serde.model.Model.to_toml()>`, and `YAML <serde.model.Model.to_yaml()>`.
See `~serde.model` for more examples. Documentation for supported fields can be
found in `~serde.field`.
found in `~serde.fields`.
"""

from serde.model import Model


__all__ = ['Model', 'error', 'field', 'validate']
__all__ = ['Model', 'exceptions', 'fields', 'validate']
__title__ = 'serde'
__version__ = '0.3.2'
__url__ = 'https://github.com/rossmacarthur/serde'
Expand Down
2 changes: 1 addition & 1 deletion src/serde/error.py → src/serde/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Exception types used in Serde.
This module contains Exception classes that are used in Serde.
"""


Expand Down
63 changes: 33 additions & 30 deletions src/serde/field.py → src/serde/fields.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""
Field types for `Models <serde.model.Model>`.
This module contains Field classes for `Models <serde.model.Model>`.

Fields handle serializing, deserializing, and validation of input values for
Model objects. They should be instantiated when assigned to the Model. Fields
Model objects. They are instantiated when assigned to the Model. Fields
support extra serialization, deserialization, and validation of values without
having to subclass `Field`.

Expand Down Expand Up @@ -31,15 +31,15 @@
>>> Person.from_dict({'name': 'Beyonce', 'fave_number': 4})
Traceback (most recent call last):
...
serde.error.ValidationError: value is not odd!
serde.exceptions.ValidationError: value is not odd!

The `create()` method can be used to generate a new Field class from arbitrary
functions without having to manually subclass a Field. For example if we wanted
a `Percent` field we would do the following.

::

>>> Percent = field.create(
>>> Percent = fields.create(
... 'Percent',
... Float,
... validators=[validate.between(0.0, 100.0)]
Expand All @@ -49,30 +49,33 @@
True

Here is an example where we subclass a field and override the serialize,
deserialize, and validate methods.
deserialize, and validate methods. Note: there is already an Email field in this
module, this is just an example of how it could be created.

::

>>> class Reversed(Field):
>>> class Email(Field):
...
... def serialize(self, value):
... return value[::-1]
... return value.strip()
...
... def deserialize(self, value):
... return value[::-1]
... return value.strip()
...
... def validate(self, value):
... assert isinstance(value, str)
... validate.email(value)

>>> class Example(Model):
... silly = Reversed(rename='sILLy')
>>> class User(Model):
... email = Email()

>>> example = Example('test')
>>> example.silly
'test'
>>> user = User(email='john@smith.com')
>>> user.email
'john@smith.com'

>>> user.to_dict()
OrderedDict([('email', 'john@smith.com')])

>>> example.to_dict()
OrderedDict([('sILLy', 'tset')])
"""

import datetime
Expand All @@ -81,8 +84,8 @@
import isodate

from serde import validate
from serde.error import SerdeError, SkipSerialization, ValidationError
from serde.util import zip_equal
from serde.exceptions import SerdeError, SkipSerialization, ValidationError
from serde.utils import zip_equal


__all__ = [
Expand Down Expand Up @@ -241,8 +244,8 @@ def __setattr__(self, name, value):
Set a named attribute on a Field.

Raises:
`~serde.error.SerdeError`: when the _name attribute is set after it
has already been set.
`~serde.exceptions.SerdeError`: when the _name attribute is set
after it has already been set.
"""
if name == '_name' and hasattr(self, '_name'):
raise SerdeError('Field instance used multiple times')
Expand Down Expand Up @@ -601,9 +604,9 @@ class Optional(Field):
::

>>> class Quote(Model):
... author = field.Optional(field.Str)
... year = field.Optional(field.Int, default=2004)
... content = field.Str()
... author = Optional(Str)
... year = Optional(Int, default=2004)
... content = Str()

>>> quote = Quote(year=2000, content='Beautiful is better than ugly.')
>>> assert quote.author is None
Expand Down Expand Up @@ -744,12 +747,12 @@ class Dict(Instance):
>>> Example({'pi': '3.1415927'})
Traceback (most recent call last):
...
serde.error.ValidationError: expected 'float' but got 'str'
serde.exceptions.ValidationError: expected 'float' but got 'str'

>>> Example.from_dict({'constants': {100: 3.1415927}})
Traceback (most recent call last):
...
serde.error.ValidationError: expected 'str' but got 'int'
serde.exceptions.ValidationError: expected 'str' but got 'int'
"""

def __init__(self, key=None, value=None, **kwargs):
Expand Down Expand Up @@ -840,12 +843,12 @@ class List(Instance):
>>> User(emails={'john@smith.com': None })
Traceback (most recent call last):
...
serde.error.ValidationError: expected 'list' but got 'dict'
serde.exceptions.ValidationError: expected 'list' but got 'dict'

>>> User.from_dict({'emails': [1234]})
Traceback (most recent call last):
...
serde.error.ValidationError: expected 'str' but got 'int'
serde.exceptions.ValidationError: expected 'str' but got 'int'
"""

def __init__(self, element=None, **kwargs):
Expand Down Expand Up @@ -937,12 +940,12 @@ class Tuple(Instance):
>>> Person('Beyonce', birthday=(4, 'September'))
Traceback (most recent call last):
...
serde.error.ValidationError: iterables have different lengths
serde.exceptions.ValidationError: iterables have different lengths

>>> Person.from_dict({'name': 'Beyonce', 'birthday': (4, 9, 1994)})
Traceback (most recent call last):
...
serde.error.ValidationError: expected 'str' but got 'int'
serde.exceptions.ValidationError: expected 'str' but got 'int'
"""

def __init__(self, *elements, **kwargs):
Expand Down Expand Up @@ -1071,7 +1074,7 @@ class Choice(Field):
>>> Car('yellow')
Traceback (most recent call last):
...
serde.error.ValidationError: 'yellow' is not a valid choice
serde.exceptions.ValidationError: 'yellow' is not a valid choice
"""

def __init__(self, choices, **kwargs):
Expand Down Expand Up @@ -1230,7 +1233,7 @@ class Uuid(Instance):
>>> User('not a uuid')
Traceback (most recent call last):
...
serde.error.ValidationError: expected 'UUID' but got 'str'
serde.exceptions.ValidationError: expected 'UUID' but got 'str'
"""

def __init__(self, **kwargs):
Expand Down