Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

moving to black #287

Merged
merged 7 commits into from Nov 15, 2018
Merged
Show file tree
Hide file tree
Changes from 6 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: 5 additions & 4 deletions Makefile
Expand Up @@ -6,16 +6,17 @@ install:
pip install -U -r requirements.txt
pip install -U .

.PHONY: isort
isort:
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
isort -rc -w 120 pydantic
isort -rc -w 120 tests
.PHONY: format
format:
isort -rc -w 120 pydantic tests
black -S -l 120 --py36 pydantic tests

.PHONY: lint
lint:
python setup.py check -rms
flake8 pydantic/ tests/
pytest pydantic -p no:sugar -q
black -S -l 120 --py36 --check pydantic tests

.PHONY: test
test:
Expand Down
5 changes: 3 additions & 2 deletions pydantic/dataclasses.py
Expand Up @@ -39,8 +39,9 @@ def _process_class(_cls, init, repr, eq, order, unsafe_hash, frozen, validate_as
return cls


def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
validate_assignment=False):
def dataclass(
_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, validate_assignment=False
):
"""
Like the python standard lib dataclasses but with type validation.

Expand Down
3 changes: 1 addition & 2 deletions pydantic/datetime_parse.py
Expand Up @@ -24,8 +24,7 @@
date_re = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$')

time_re = re.compile(
r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
)

datetime_re = re.compile(
Expand Down
5 changes: 1 addition & 4 deletions pydantic/env_settings.py
Expand Up @@ -28,10 +28,7 @@ class BaseSettings(BaseModel):
"""

def __init__(self, **values):
values = {
**self._substitute_environ(),
**values,
}
values = {**self._substitute_environ(), **values}
super().__init__(**values)

def _substitute_environ(self):
Expand Down
18 changes: 4 additions & 14 deletions pydantic/error_wrappers.py
@@ -1,10 +1,7 @@
import json
from functools import lru_cache

__all__ = (
'ErrorWrapper',
'ValidationError',
)
__all__ = ('ErrorWrapper', 'ValidationError')


class ErrorWrapper:
Expand Down Expand Up @@ -35,11 +32,7 @@ def type_(self):
def dict(self, *, loc_prefix=None):
loc = self.loc if loc_prefix is None else loc_prefix + self.loc

d = {
'loc': loc,
'msg': self.msg,
'type': self.type_,
}
d = {'loc': loc, 'msg': self.msg, 'type': self.type_}

if self.ctx is not None:
d['ctx'] = self.ctx
Expand All @@ -48,7 +41,7 @@ def dict(self, *, loc_prefix=None):


class ValidationError(ValueError):
__slots__ = 'raw_errors',
__slots__ = ('raw_errors',)

def __init__(self, errors):
self.raw_errors = errors
Expand All @@ -67,10 +60,7 @@ def __str__(self):


def display_errors(errors):
return '\n'.join(
f'{_display_error_loc(e)}\n {e["msg"]} ({_display_error_type_and_ctx(e)})'
for e in errors
)
return '\n'.join(f'{_display_error_loc(e)}\n {e["msg"]} ({_display_error_type_and_ctx(e)})' for e in errors)


def _display_error_loc(error):
Expand Down
103 changes: 52 additions & 51 deletions pydantic/fields.py
Expand Up @@ -38,7 +38,8 @@ class Schema:
"""
Used to provide extra information about a field in a model schema.
"""
__slots__ = 'default', 'alias', 'title', 'choice_names', 'extra',

__slots__ = 'default', 'alias', 'title', 'choice_names', 'extra'

def __init__(self, default, *, alias=None, title=None, choice_names=None, **extra):
self.default = default
Expand All @@ -50,22 +51,38 @@ def __init__(self, default, *, alias=None, title=None, choice_names=None, **extr

class Field:
__slots__ = (
'type_', 'sub_fields', 'key_field', 'validators', 'whole_pre_validators', 'whole_post_validators',
'default', 'required', 'model_config', 'name', 'alias', '_schema', 'validate_always', 'allow_none', 'shape',
'class_validators', 'parse_json'
'type_',
'sub_fields',
'key_field',
'validators',
'whole_pre_validators',
'whole_post_validators',
'default',
'required',
'model_config',
'name',
'alias',
'_schema',
'validate_always',
'allow_none',
'shape',
'class_validators',
'parse_json',
)

def __init__(
self, *,
name: str,
type_: Type,
class_validators: List[Validator],
default: Any,
required: bool,
model_config: Any,
alias: str=None,
allow_none: bool=False,
schema: Schema=None):
self,
*,
name: str,
type_: Type,
class_validators: List[Validator],
default: Any,
required: bool,
model_config: Any,
alias: str = None,
allow_none: bool = False,
schema: Schema = None,
):

self.name: str = name
self.alias: str = alias or name
Expand Down Expand Up @@ -136,10 +153,7 @@ def prepare(self):
self._populate_validators()

def schema(self, by_alias=True):
s = dict(
title=self._schema.title or self.alias.title(),
required=self.required,
)
s = dict(title=self._schema.title or self.alias.title(), required=self.required)

if not self.required and self.default is not None:
s['default'] = self.default
Expand All @@ -151,26 +165,17 @@ def schema(self, by_alias=True):

def type_schema(self, by_alias):
if self.shape is Shape.LIST:
return {
'type': 'list',
'item_type': self._singleton_schema(by_alias),
}
return {'type': 'list', 'item_type': self._singleton_schema(by_alias)}
if self.shape is Shape.SET:
return {
'type': 'set',
'item_type': self._singleton_schema(by_alias),
}
return {'type': 'set', 'item_type': self._singleton_schema(by_alias)}
elif self.shape is Shape.MAPPING:
return {
'type': 'mapping',
'item_type': self._singleton_schema(by_alias),
'key_type': self.key_field.type_schema(by_alias)
'key_type': self.key_field.type_schema(by_alias),
}
elif self.shape is Shape.TUPLE:
return {
'type': 'tuple',
'item_types': [sf.type_schema(by_alias) for sf in self.sub_fields],
}
return {'type': 'tuple', 'item_types': [sf.type_schema(by_alias) for sf in self.sub_fields]}
else:
assert self.shape is Shape.SINGLETON, self.shape
return self._singleton_schema(by_alias)
Expand All @@ -180,20 +185,16 @@ def _singleton_schema(self, by_alias):
if len(self.sub_fields) == 1:
return self.sub_fields[0].type_schema(by_alias)
else:
return {
'type': 'any_of',
'types': [sf.type_schema(by_alias) for sf in self.sub_fields]
}
return {'type': 'any_of', 'types': [sf.type_schema(by_alias) for sf in self.sub_fields]}
elif self.type_ is Any:
return 'any'
elif issubclass(self.type_, Enum):
choice_names = self._schema.choice_names or {}
return {
'type': display_as_type(self.type_),
'choices': [
(v.value, choice_names.get(v.value) or k.title())
for k, v in self.type_.__members__.items()
]
(v.value, choice_names.get(v.value) or k.title()) for k, v in self.type_.__members__.items()
],
}

type_schema_method = getattr(self.type_, 'type_schema', None)
Expand Down Expand Up @@ -225,9 +226,7 @@ def _populate_sub_fields(self):

if issubclass(origin, Tuple):
self.shape = Shape.TUPLE
self.sub_fields = [
self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(self.type_.__args__)
]
self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(self.type_.__args__)]
return

if issubclass(origin, List):
Expand Down Expand Up @@ -262,8 +261,11 @@ def _populate_validators(self):
get_validators = getattr(self.type_, 'get_validators', None)
v_funcs = (
*tuple(v.func for v in self.class_validators if not v.whole and v.pre),
*(get_validators() if get_validators else find_validators(self.type_,
self.model_config.arbitrary_types_allowed)),
*(
get_validators()
if get_validators
else find_validators(self.type_, self.model_config.arbitrary_types_allowed)
),
*tuple(v.func for v in self.class_validators if not v.whole and not v.pre),
)
self.validators = self._prep_vals(v_funcs)
Expand All @@ -277,17 +279,14 @@ def _prep_vals(self, v_funcs):
for f in v_funcs:
if not f or (self.allow_none and f is not_none_validator):
continue
v.append((
_get_validator_signature(f),
f,
))
v.append((_get_validator_signature(f), f))
return tuple(v)

def validate(self, v, values, *, loc, cls=None): # noqa: C901 (ignore complexity)
if self.allow_none and v is None:
return None, None

loc = loc if isinstance(loc, tuple) else (loc, )
loc = loc if isinstance(loc, tuple) else (loc,)

if self.parse_json:
v, error = self._validate_json(v, loc)
Expand Down Expand Up @@ -459,6 +458,8 @@ def _get_validator_signature(validator):
signature.bind(1, values=2, config=3, field=4)
return ValidatorSignature.VALUE_KWARGS
except TypeError as e:
raise errors_.ConfigError(f'Invalid signature for validator {validator}: {signature}, should be: '
f'(value) or (value, *, values, config, field) or for class validators '
f'(cls, value) or (cls, value, *, values, config, field)') from e
raise errors_.ConfigError(
f'Invalid signature for validator {validator}: {signature}, should be: '
f'(value) or (value, *, values, config, field) or for class validators '
f'(cls, value) or (cls, value, *, values, config, field)'
) from e
1 change: 1 addition & 0 deletions pydantic/json.py
Expand Up @@ -27,6 +27,7 @@ def isoformat(o):

def pydantic_encoder(obj):
from .main import BaseModel

if isinstance(obj, BaseModel):
return obj.dict()
elif isinstance(obj, Enum):
Expand Down