API Reference Documentation

Contents

class conformity.fields.basic.Base[source]

Bases: object

The base Conformity field from which all Conformity fields must inherit, this defines a simple interface for getting a list of validation errors and recursively introspecting the schema. All fields should accept a description argument for use in documentation and introspection.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

__init__() → None[source]

Initialize self. See help(type(self)) for accurate signature.

conformity.fields.basic.attr_is_conformity_field() → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is a Conformity field (extends Base).

class conformity.fields.basic.Constant(*args: Any, **kwargs: Any)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value exactly matches the constant value supplied or, if multiple constant values are supplied, exactly matches one of those values.

introspect_type = 'constant'[source]
__init__(*args: Any, **kwargs: Any) → None[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

class conformity.fields.basic.Anything(description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that allows the value to be literally anything.

introspect_type = 'anything'[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

__init__(description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.Hashable(description=None)[source]

Bases: conformity.fields.basic.Anything

Conformity field that ensures that the value is hashable (hash(...) can be called on the value without error).

introspect_type = 'hashable'[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

__init__(description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.Boolean(description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a boolean.

introspect_type = 'boolean'[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

__init__(description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.Integer(gt: Union[int, float, decimal.Decimal, None] = None, gte: Union[int, float, decimal.Decimal, None] = None, lt: Union[int, float, decimal.Decimal, None] = None, lte: Union[int, float, decimal.Decimal, None] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is an integer and optionally enforces boundaries for that integer with the gt, gte, lt, and lte arguments.

valid_type = (<class 'int'>,)[source]
valid_noun = 'an integer'[source]
introspect_type = 'integer'[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

__init__(gt: Union[int, float, decimal.Decimal, None] = None, gte: Union[int, float, decimal.Decimal, None] = None, lt: Union[int, float, decimal.Decimal, None] = None, lte: Union[int, float, decimal.Decimal, None] = None, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.Float(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.basic.Integer

Conformity field that ensures that the value is a float and optionally enforces boundaries for that float with the gt, gte, lt, and lte arguments.

valid_type = (<class 'int'>, <class 'float'>)[source]
valid_noun = 'a float'[source]
introspect_type = 'float'[source]
__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.Decimal(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.basic.Integer

Conformity field that ensures that the value is a decimal.Decimal and optionally enforces boundaries for that decimal with the gt, gte, lt, and lte arguments.

valid_type[source]

alias of decimal.Decimal

valid_noun = 'a decimal'[source]
introspect_type = 'decimal'[source]
__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.UnicodeString(min_length: Optional[int] = None, max_length: Optional[int] = None, description: Optional[str] = None, allow_blank: bool = True)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a unicode string (str in Python 3, unicode in Python 2) and optionally enforces minimum and maximum lengths with the min_length, max_length, and allow_blank arguments.

valid_type[source]

alias of builtins.str

valid_noun = 'unicode string'[source]
introspect_type = 'unicode'[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

__init__(min_length: Optional[int] = None, max_length: Optional[int] = None, description: Optional[str] = None, allow_blank: bool = True)[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.ByteString(min_length=None, max_length=None, description=None, allow_blank=True)[source]

Bases: conformity.fields.basic.UnicodeString

Conformity field that ensures that the value is a byte string (bytes in Python 3, str in Python 2) and optionally enforces minimum and maximum lengths with the min_length, max_length, and allow_blank arguments.

valid_type[source]

alias of builtins.bytes

valid_noun = 'byte string'[source]
introspect_type = 'bytes'[source]
__init__(min_length=None, max_length=None, description=None, allow_blank=True) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.basic.UnicodeDecimal(description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a unicode string that is also a valid decimal and can successfully be converted to a decimal.Decimal.

introspect_type = 'unicode_decimal'[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

__init__(description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

class conformity.fields.country.CountryCodeField(code_filter: Callable[[~AnyStr], bool] = <function CountryCodeField.<lambda>>, **kwargs: Any)[source]

Bases: conformity.fields.basic.Constant

Conformity field that ensures that the value is a valid ISO 3166 country codes. It permits only current countries according to the installed version of PyCountry and uses the ISO 3166 alpha-2 codes. This field requires that PyCountry be installed.

__init__(code_filter: Callable[[AnyStr], bool] = <function CountryCodeField.<lambda>>, **kwargs: Any) → None[source]
Parameters

code_filter – If specified, will be called to further filter the available country codes

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect_type = 'country_code_field'[source]
class conformity.fields.currency.Amount(valid_currencies: AbstractSet[str] = frozenset(), gt: Optional[int] = None, gte: Optional[int] = None, lt: Optional[int] = None, lte: Optional[int] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is an instance of currint.Amount and optionally enforces boundaries for that amount with the valid_currencies, gt, gte, lt, and lte arguments. This field requires that Currint be installed.

__init__(valid_currencies: AbstractSet[str] = frozenset({}), gt: Optional[int] = None, gte: Optional[int] = None, lt: Optional[int] = None, lte: Optional[int] = None, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'currint.Amount'[source]
class conformity.fields.currency.AmountRequestDictionary(valid_currencies: Iterable[str] = None, gt: Optional[int] = None, gte: Optional[int] = None, lt: Optional[int] = None, lte: Optional[int] = None, description: Optional[str] = None, *args: Any, **kwargs: Any)[source]

Bases: conformity.fields.structures.Dictionary

Conformity field that ensures that the value is a dictionary containing exactly fields 'currency' and 'value' and optionally enforces boundaries for those values with the valid_currencies, gt, gte, lt, and lte arguments. This field requires that Currint be installed. No other arguments are supported; *args and **kwargs are deprecated and will be removed in Conformity 2.0.0.

__init__(valid_currencies: Iterable[str] = None, gt: Optional[int] = None, gte: Optional[int] = None, lt: Optional[int] = None, lte: Optional[int] = None, description: Optional[str] = None, *args: Any, **kwargs: Any) → None[source]

Construct the field.

Parameters
  • valid_currencies – An iterable of valid currencies (if not specified, all valid currencies will be used)

  • gt – If specified, the value must be greater than this

  • gte – If specified, the value must be greater than or equal to this

  • lt – If specified, the value must be less than this

  • lte – If specified, the value must be less than or equal to this

  • description – The description for documentation

  • args – Deprecated, unused, and will be removed in version 2.0.0

  • kwargs – Deprecated, unused, and will be removed in version 2.0.0

class conformity.fields.currency.AmountResponseDictionary(description: Optional[str] = None, major_value_required: bool = True, display_required: bool = True)[source]

Bases: conformity.fields.structures.Dictionary

Conformity field that ensures that the value is a dictionary containing at least fields 'currency' and 'value' and optionally fields 'major_value' and 'display'. This field requires that Currint be installed.

__init__(description: Optional[str] = None, major_value_required: bool = True, display_required: bool = True) → None[source]

Construct the field.

Parameters
  • description – The description for documentation

  • major_value_required – By default, 'major_value' is a required field in the response, but setting this to False makes it optional

  • display_required – By default, 'display' is a required field in the response, but setting this to False makes it optional

class conformity.fields.currency.AmountString(valid_currencies: AbstractSet[str] = frozenset(), gt: Optional[int] = None, gte: Optional[int] = None, lt: Optional[int] = None, lte: Optional[int] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a unicode string matching the format CUR,1234 or CUR:1234, where the part before the delimiter is a valid currency and the part after the delimiter is an integer. It also optionally enforces boundaries for those values with the valid_currencies, gt, gte, lt, and lte arguments. This field requires that Currint be installed.

__init__(valid_currencies: AbstractSet[str] = frozenset({}), gt: Optional[int] = None, gte: Optional[int] = None, lt: Optional[int] = None, lte: Optional[int] = None, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'currency_amount_string'[source]
class conformity.fields.email.EmailAddress(message: None = None, code: None = None, whitelist: Iterable[str] = None, **kwargs: Any)[source]

Bases: conformity.fields.basic.UnicodeString

Conformity field that ensures that the value is a unicode string that is a valid email address according to RFC 2822 and optionally accepts non-compliant fields listed in the whitelist argument. Substantially copied from Django (v2.0.x): https://github.com/django/django/blob/stable/2.0.x/django/core/validators.py#L164.

__init__(message: None = None, code: None = None, whitelist: Iterable[str] = None, **kwargs: Any) → None[source]

Construct a new email address field.

Parameters
  • message – Deprecated, unused, and will be removed in version 2.0.0

  • code – Deprecated, unused, and will be removed in version 2.0.0

  • whitelist – If specified, an invalid domain part will be permitted if it is in this list

code = None[source]
domain_regex = re.compile('((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\\Z', re.IGNORECASE)[source]
domain_whitelist = frozenset({'localhost'})[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'email_address'[source]
ip_schema = IPAddress()[source]
classmethod is_domain_valid(domain_part: str) → bool[source]
literal_regex = re.compile('\\[([A-f0-9:.]+)\\]\\Z', re.IGNORECASE)[source]
message = None[source]
user_regex = re.compile('(^[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+)*\\Z|^"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-\\011\\013\\014\\016-\\177])*"\\Z)', re.IGNORECASE)[source]
class conformity.fields.geo.Latitude(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.basic.Float

Conformity field that ensures that the value is a float within the normal boundaries of a geographical latitude on an ellipsoid or sphere.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.geo.Longitude(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.basic.Float

Conformity field that ensures that the value is a float within the normal boundaries of a geographical longitude on an ellipsoid or sphere.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.net.IPAddress(**kwargs: Any)[source]

Bases: conformity.fields.meta.Any

Conformity field that ensures that the value is a unicode string that is a valid IPv4 or IPv6 address.

__init__(**kwargs: Any) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.net.IPv4Address(min_length=None, max_length=None, description=None, allow_blank=True)[source]

Bases: conformity.fields.basic.UnicodeString

Conformity field that ensures that the value is a unicode string that is a valid IPv4 address.

__init__(min_length=None, max_length=None, description=None, allow_blank=True) → None[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'ipv4_address'[source]
class conformity.fields.net.IPv6Address(min_length=None, max_length=None, description=None, allow_blank=True)[source]

Bases: conformity.fields.basic.UnicodeString

Conformity field that ensures that the value is a unicode string that is a valid IPv6 address.

__init__(min_length=None, max_length=None, description=None, allow_blank=True) → None[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

static expand_ipv6_address(value: str) → str[source]

Expands a potentially-shortened IPv6 address into its full length

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'ipv6_address'[source]
class conformity.fields.temporal.Date(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.temporal.TemporalBase

Conformity field that ensures that the value is a datetime.date instance and optionally enforces boundaries for that date with the gt, gte, lt, and lte arguments, which must also be date instances if specified.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'date'[source]
valid_noun = 'datetime.date'[source]
valid_types = frozenset({<class 'datetime.date'>})[source]
class conformity.fields.temporal.DateTime(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.temporal.TemporalBase

Conformity field that ensures that the value is a datetime.datetime instance and optionally enforces boundaries for that datetime with the gt, gte, lt, and lte arguments, which must also be datetime instances if specified.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'datetime'[source]
valid_noun = 'datetime.datetime'[source]
valid_types = frozenset({<class 'datetime.datetime'>})[source]
class conformity.fields.temporal.TZInfo(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.temporal.TemporalBase

Conformity field that ensures that the value is a datetime.tzinfo instance. It has gt, gte, lt, and lte arguments, but they cannot be used, are deprecated, and will be removed in Conformity 2.0.0.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'tzinfo'[source]
valid_isinstance[source]

alias of datetime.tzinfo

valid_noun = 'datetime.tzinfo'[source]
valid_types = frozenset({<class 'datetime.tzinfo'>})[source]
class conformity.fields.temporal.TemporalBase(gt: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, gte: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, lt: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, lte: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Common base class for all temporal types. Cannot be used on its own without extension.

__init__(gt: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, gte: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, lt: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, lte: Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta] = None, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = None[source]
valid_isinstance = None[source]
valid_noun = None[source]
valid_types = None[source]
class conformity.fields.temporal.Time(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.temporal.TemporalBase

Conformity field that ensures that the value is a datetime.time instance and optionally enforces boundaries for that time with the gt, gte, lt, and lte arguments, which must also be time instances if specified.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'time'[source]
valid_noun = 'datetime.time'[source]
valid_types = frozenset({<class 'datetime.time'>})[source]
class conformity.fields.temporal.TimeDelta(gt=None, gte=None, lt=None, lte=None, description=None)[source]

Bases: conformity.fields.temporal.TemporalBase

Conformity field that ensures that the value is a datetime.timedelta instance and optionally enforces boundaries for that timedelta with the gt, gte, lt, and lte arguments, which must also be timedelta instances if specified.

__init__(gt=None, gte=None, lt=None, lte=None, description=None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'timedelta'[source]
valid_noun = 'datetime.timedelta'[source]
valid_types = frozenset({<class 'datetime.timedelta'>})[source]
class conformity.fields.structures.AdditionalCollectionValidator[source]

Bases: typing.Generic

Conformity fields validating collections can have an additional custom validator that can perform extra checks across the entire collection, such as ensuring that values that need to refer to other values in the same collection properly match. This is especially helpful to be able to avoid duplicating the existing collection validation in Conformity’s structure fields.

abstract errors(value: ~VT) → List[conformity.error.Error][source]

Called after the collection has otherwise passed validation, and not called if the collection has not passed its normal validation.

Parameters

value – The value to be validated.

Returns

A list of errors encountered with this value.

class conformity.fields.structures.Dictionary(contents: Mapping[Hashable, conformity.fields.basic.Base] = None, optional_keys: Union[Tuple[Hashable, ...], FrozenSet[Hashable]] = frozenset(), allow_extra_keys: bool = None, description: Optional[str] = None, additional_validator: Union[conformity.fields.structures.AdditionalCollectionValidator[Mapping[Hashable, Any]], None] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a dictionary with a specific set of keys and value that validate with the Conformity fields associated with those keys (contents). Keys are required unless they are listed in the optional_keys argument. No extra keys are allowed unless the allow_extra_keys argument is set to True.

If the contents argument is an instance of OrderedDict, the field introspection will include a display_order list of keys matching the order they exist in the OrderedDict, and errors will be reported in the order the keys exist in the OrderedDict. Order will be maintained for any calls to extend as long as those calls also use OrderedDict. Ordering behavior is undefined otherwise. This field does NOT enforce that the value it validates presents keys in the same order. OrderedDict is used strictly for documentation and error-object-ordering purposes only.

__init__(contents: Mapping[Hashable, conformity.fields.basic.Base] = None, optional_keys: Union[Tuple[Hashable, ...], FrozenSet[Hashable]] = frozenset({}), allow_extra_keys: bool = None, description: Optional[str] = None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[typing.Mapping[typing.Hashable, typing.Any]][Mapping[Hashable, Any]]] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

extend(contents: Union[Mapping[Hashable, conformity.fields.basic.Base], None] = None, optional_keys: Union[Tuple[Hashable, ...], FrozenSet[Hashable], None] = None, allow_extra_keys: Optional[bool] = None, description: Optional[str] = None, replace_optional_keys: bool = False, additional_validator: Union[conformity.fields.structures.AdditionalCollectionValidator[Mapping[Hashable, Any]], None] = None) → <class 'conformity.fields.structures.Dictionary'>[source]

This method allows you to create a new Dictionary that extends the current Dictionary with additional contents and/or optional keys, and/or replaces the allow_extra_keys and/or description attributes.

Parameters
  • contents – More contents, if any, to extend the current contents

  • optional_keys – More optional keys, if any, to extend the current optional keys

  • allow_extra_keys – If non-None, this overrides the current allow_extra_keys attribute

  • description – If non-None, this overrides the current description attribute

  • replace_optional_keys – If True, then the optional_keys argument will completely replace, instead of extend, the current optional keys

  • additional_validator – If non-None, this overrides the current additional_validator attribute

Returns

A new Dictionary extended from the current Dictionary based on the supplied arguments

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'dictionary'[source]
class conformity.fields.structures.List(contents, max_length=None, min_length=None, description=None, additional_validator: Union[conformity.fields.structures.AdditionalCollectionValidator[list], None] = None)[source]

Bases: conformity.fields.structures._BaseSequenceOrSet

__init__(contents, max_length=None, min_length=None, description=None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[list][list]] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'list'[source]
type_error = 'Not a list'[source]
valid_types[source]

alias of builtins.list

class conformity.fields.structures.SchemalessDictionary(key_type: <class 'conformity.fields.basic.Base'> = NOTHING, value_type: <class 'conformity.fields.basic.Base'> = NOTHING, max_length: Optional[int] = None, min_length: Optional[int] = None, description: Optional[str] = None, additional_validator: Union[conformity.fields.structures.AdditionalCollectionValidator[Mapping[Hashable, Any]], None] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a dictionary of any keys and values, but optionally enforcing that the keys pass the Conformity validation specified with the key_type argument and/or that the values pass the Conformity validation specified with the value_type argument. Size of the dictionary can also be constrained with the optional max_length and min_length arguments.

__init__(key_type: conformity.fields.basic.Base = NOTHING, value_type: conformity.fields.basic.Base = NOTHING, max_length: Optional[int] = None, min_length: Optional[int] = None, description: Optional[str] = None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[typing.Mapping[typing.Hashable, typing.Any]][Mapping[Hashable, Any]]] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'schemaless_dictionary'[source]
class conformity.fields.structures.Sequence(contents, max_length=None, min_length=None, description=None, additional_validator: Union[conformity.fields.structures.AdditionalCollectionValidator[Sequence], None] = None)[source]

Bases: conformity.fields.structures._BaseSequenceOrSet

__init__(contents, max_length=None, min_length=None, description=None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[typing.Sequence][Sequence]] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'sequence'[source]
type_error = 'Not a sequence'[source]
valid_types = typing.Sequence[source]
class conformity.fields.structures.Set(contents, max_length=None, min_length=None, description=None, additional_validator: Union[conformity.fields.structures.AdditionalCollectionValidator[AbstractSet], None] = None)[source]

Bases: conformity.fields.structures._BaseSequenceOrSet

Conformity field that ensures that the value is an abstract set of items that all pass validation with the Conformity field passed to the contents argument and optionally establishes boundaries for that list with the max_length and min_length arguments.

class LazyPointer(_, value)[source]

Bases: object

__init__(_, value)[source]

Initialize self. See help(type(self)) for accurate signature.

__init__(contents, max_length=None, min_length=None, description=None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[typing.AbstractSet][AbstractSet]] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

introspect_type = 'set'[source]
type_error = 'Not a set or frozenset'[source]
valid_types = typing.AbstractSet[source]
class conformity.fields.structures.Tuple(*contents: <class 'conformity.fields.basic.Base'>, **kwargs: Any)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is a tuple with the same number of arguments as the number of positional arguments passed to this field, and that each argument passes validation with the corresponding Conformity field provided to the positional arguments.

__init__(*contents: conformity.fields.basic.Base, **kwargs: Any) → None[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'tuple'[source]
class conformity.fields.meta.All(*args: <class 'conformity.fields.basic.Base'>, **kwargs: Any)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value passes validation with at all of the Conformity fields passed as positional arguments.

__init__(*args: conformity.fields.basic.Base, **kwargs: Any) → None[source]

Initialize self. See help(type(self)) for accurate signature.

description = None[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'all'[source]
class conformity.fields.meta.Any(*args: <class 'conformity.fields.basic.Base'>, **kwargs: Any)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value passes validation with at least one of the Conformity fields passed as positional arguments.

__init__(*args: conformity.fields.basic.Base, **kwargs: Any) → None[source]

Initialize self. See help(type(self)) for accurate signature.

description = None[source]
errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'any'[source]
class conformity.fields.meta.BooleanValidator(validator: Callable[[Any], bool], validator_description: str, error: str, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value passes validation with the typing.Callable[[typing.Any], bool] validator argument passed in to it.

__init__(validator: Callable[[Any], bool], validator_description: str, error: str, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'boolean_validator'[source]
class conformity.fields.meta.ClassConfigurationSchema(base_class: Optional[Type] = None, default_path: Optional[str] = None, description: Optional[str] = None, eager_default_validation: bool = True, add_class_object_to_dict: bool = True)[source]

Bases: conformity.fields.basic.Base

A special-case dictionary field that accepts exactly two keys: path (a TypePath-validated string) and kwargs (a Dictionary-or-subclass-validated dict) that can discover initialization schema from classes and validate that schema prior to instantiation. By default, the dictionary is mutated to add an object key containing the resolved class, but this behavior can be disabled by specifying add_class_object_to_dict=False to the field arguments. If you experience circular dependency errors when using this field, you can mitigate this by specifying eager_default_validation=False to the field arguments.

Typical usage would be as follows, in Python pseudocode:

class BaseThing:
    ...

@fields.ClassConfigurationSchema.provider(fields.Dictionary({...}, ...))
class Thing1(BaseThing):
    ...

@fields.ClassConfigurationSchema.provider(fields.Dictionary({...}, ...))
class Thing2(BaseThing):
    ...

settings = get_settings_from_something()
schema = fields.ClassConfigurationSchema(base_class=BaseThing)
errors = schema.errors(**settings[kwargs])
if errors:
    ... handle errors ...

thing = settings['object'](settings)

Another approach, using the helper method on the schema, simplifies that last part:

schema = fields.ClassConfigurationSchema(base_class=BaseThing)
thing = schema.instantiate_from(get_settings_from_something())  # raises ValidationError

However, note that, in both cases, instantiation is not nested. If the settings schema Dictionary on some class has a key (or further down) whose value is another ClassConfigurationSchema, code that consumes those settings will also have to instantiate objects from those settings. Validation, however, will be nested as in all other things Conformity.

__init__(base_class: Optional[Type] = None, default_path: Optional[str] = None, description: Optional[str] = None, eager_default_validation: bool = True, add_class_object_to_dict: bool = True)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

initiate_cache_for(path: str) → None[source]
instantiate_from(configuration: MutableMapping[Hashable, Any]) → Any[source]
introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'class_config_dictionary'[source]
static provider(schema: <class 'conformity.fields.structures.Dictionary'>) → Callable[[Type], Type][source]
switch_field_schema = TypePath(value_schema=TypeReference(base_classes=<class 'object'>, description=None), description=None)[source]
class conformity.fields.meta.Null[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is null / None. Useful as a return type, to indicate that a function returns nothing, for example.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'null'[source]
class conformity.fields.meta.Nullable(field: <class 'conformity.fields.basic.Base'>)[source]

Bases: conformity.fields.basic.Base

Conformity field that allows a null / None value and delegates validation the field type passed as the first positional argument for all non-null values. Introspection is a dictionary with “type” set to “nullable” and key “nullable” set to the introspection of the first positional argument.

__init__(field: conformity.fields.basic.Base)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'nullable'[source]
class conformity.fields.meta.ObjectInstance(valid_type: Union[Type, Tuple[Type, ...]], description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is an instance of the given valid_type.

__init__(valid_type: Union[Type, Tuple[Type, ...]], description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'object_instance'[source]
class conformity.fields.meta.Polymorph(switch_field: str, contents_map: Mapping[Hashable, conformity.fields.basic.Base], description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

A Conformity field which has one of a set of possible contents based on a field within it (which must be accessible via Mapping key lookups).

__init__(switch_field: str, contents_map: Mapping[Hashable, conformity.fields.basic.Base], description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'polymorph'[source]
class conformity.fields.meta.PythonPath(value_schema: Optional[conformity.fields.basic.Base] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that accepts only a unicode path to an importable Python type, function, or variable, including the full path to the enclosing module. Both ‘.’ and ‘:’ are recognized as valid separators between module name and item name, but if the item is not a top-level member of the module, it can only be accessed by using ‘:’ as the separator.

All of the following are valid type name formats:

foo.bar.MyClass foo.bar:MyClass foo.bar.my_function foo.bar.MY_CONSTANT foo.bar:MyClass.MY_CONSTANT baz.qux:ParentClass.SubClass

This field performs two validations: First that the path is a unicode string, and second that the item is importable (exists). If you later need to actually access that item, you can use the resolve_python_path static method. Imported items are cached for faster future lookup.

You can optionally specify a value_schema argument to this field, itself a Conformity field, which will perform further validation on the value of the imported item.

__init__(value_schema: Optional[conformity.fields.basic.Base] = None, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'python_path'[source]
classmethod resolve_python_path(type_path: str) → Any[source]
class conformity.fields.meta.TypePath(base_classes: Union[Type, Tuple[Type, ...], None] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.meta.PythonPath

Conformity field that accepts only a unicode path to an importable Python type, including the full path to the enclosing module. Both ‘.’ and ‘:’ are recognized as a valid separator between module name and type name.

All of the following are valid type name formats:

foo.bar.MyClass foo.bar:MyClass baz.qux:ParentClass.SubClass

This field actually validates that the type is importable, exists, and is a type, possibly one that subclasses one or more base_classes.

This is a special convenience PythonPath extension for expecting the imported item to be a type.

__init__(base_classes: Union[Type, Tuple[Type, ...], None] = None, description: Optional[str] = None) → None[source]

Initialize self. See help(type(self)) for accurate signature.

class conformity.fields.meta.TypeReference(base_classes: Union[Type, Tuple[Type, ...], None] = None, description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Base

Conformity field that ensures that the value is an instance of type and, optionally, that the value is a subclass of the type or types specified by base_classes.

__init__(base_classes: Union[Type, Tuple[Type, ...], None] = None, description: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

errors(value: Any) → List[conformity.error.Error][source]

Returns a list of errors with the value. An empty return means that it’s valid.

introspect() → Dict[str, Union[int, float, bool, str, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, None, List[Any], Dict[Any, Any]]][source]

Returns a JSON-serializable dictionary containing introspection data that can be used to document the schema.

introspect_type = 'type_reference'[source]
class conformity.fields.logging.PythonLogLevel(description: Optional[str] = None)[source]

Bases: conformity.fields.basic.Constant

A pre-defined Constant field with all the possible Python log levels populated. All you need is a description for documentation.

__init__(description: Optional[str] = None) → None[source]

Constructs a PythonLogLevel field.

Parameters

description – The description for documentation

PYTHON_LOGGING_CONFIG_SCHEMA = pre-defined Conformity schema conformity.fields.logging.PYTHON_LOGGING_CONFIG_SCHEMA

strict dict: Settings to enforce the standard Python logging dictionary-based configuration, as you would load with logging.config.dictConfig(). For more information than the documentation here, see https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema.

  • version - integer: (no description) (additional information: {'gte': 1, 'lte': 1})

  • formatters - flexible dict: This defines a mapping of logging formatter names to formatter configurations. The format key specifies the log format and the datefmt key specifies the date format.

    keys

    unicode: (no description)

    values

    strict dict: (no description)

    Optional keys: datefmt

  • filters - flexible dict: This defines a mapping of logging filter names to filter configurations. If a config has only the name key, then logging.Filter will be instantiated with that argument. You can specify a () key (yes, really) to override the default logging.Filter class with a custom filter implementation (which should extend logging.Filter). Extra keys are allowed only for custom implementations having extra constructor arguments matching those key names.

    keys

    unicode: (no description)

    values

    strict dict: (no description)

    • () - a unicode string importable Python path in the format “foo.bar.MyClass”, “foo.bar:YourClass.CONSTANT”, etc. The optional, fully-qualified name of the class extending logging.Filter, used to override the default class logging.Filter. The imported item at the specified path must match the following schema:

      schema

      a Python type that is a subclass of the following class or classes: logging.Filter.

    • name - unicode: The optional filter name which will be passed to the name argument of the logging.Filter class.

    Extra keys of any value are allowed. Optional keys: (), name

  • handlers - flexible dict: This defines a mapping of logging handler names to handler configurations. The class key is the importable Python path to the class extending logging.Handler. The level and filters keys apply to all handlers. The formatter key is valid for all handlers, but not all handlers will use it. Extra keys are allowed only for handlers having extra constructor arguments matching those key names.

    keys

    unicode: (no description)

    values

    strict dict: (no description)

    • class - a unicode string importable Python path in the format “foo.bar.MyClass”, “foo.bar:YourClass.CONSTANT”, etc. The fully-qualified name of the class extending logging.Handler. The imported item at the specified path must match the following schema:

      schema

      a Python type that is a subclass of the following class or classes: logging.Handler.

    • filters - list: A list of references to keys from filters for assigning those filters to this handler.

      values

      unicode: (no description)

    • formatter - unicode: A reference to a key from formatters for assigning that formatter to this handler.

    • level - constant: The logging level at or above which this handler will emit logging events. (additional information: {'values': ['CRITICAL', 'DEBUG', 'ERROR', 'INFO', 'WARNING']})

    Extra keys of any value are allowed. Optional keys: filters, formatter, level

  • loggers - flexible dict: This defines a mapping of logger names to logger configurations. A log event not handled by one of these configured loggers (if any) will instead be handled by the root logger. A log event handled by one of these configured loggers may still be handled by another logger or the root logger unless its propagate key is set to False.

    keys

    unicode: (no description)

    values

    strict dict: (no description)

    • filters - list: A list of references to keys from filters for assigning those filters to this logger.

      values

      unicode: (no description)

    • handlers - list: A list of references to keys from handlers for assigning those handlers to this logger.

      values

      unicode: (no description)

    • level - constant: The logging level at or above which this logger will handle logging events and send them to its configured handlers. (additional information: {'values': ['CRITICAL', 'DEBUG', 'ERROR', 'INFO', 'WARNING']})

    • propagate - boolean: Whether logging events handled by this logger should propagate to other loggers and/or the root logger. Defaults to True.

    Optional keys: filters, handlers, level, propagate

  • root - strict dict: (no description)

    • filters - list: A list of references to keys from filters for assigning those filters to this logger.

      values

      unicode: (no description)

    • handlers - list: A list of references to keys from handlers for assigning those handlers to this logger.

      values

      unicode: (no description)

    • level - constant: The logging level at or above which this logger will handle logging events and send them to its configured handlers. (additional information: {'values': ['CRITICAL', 'DEBUG', 'ERROR', 'INFO', 'WARNING']})

    Optional keys: filters, handlers, level

  • incremental - boolean: Whether this configuration should be considered incremental to any existing configuration. It defaults to False and it is rare that you should ever need to change that.

  • disable_existing_loggers - boolean: Whether all existing loggers (objects obtained from logging.getLogger()) should be disabled when this logging config is loaded. Take our advice and always set this to False. It defaults to True and you almost never want that, because loggers in already-loaded modules will stop working.

Optional keys: disable_existing_loggers, filters, formatters, handlers, incremental, loggers, root, version

class conformity.error.Error(message: str, code: str = 'INVALID', pointer: Optional[str] = None)[source]

Bases: object

Represents an error found validating against the schema.

__init__(message: str, code: str = 'INVALID', pointer: Optional[str] = None)[source]

Initialize self. See help(type(self)) for accurate signature.

exception conformity.error.KeywordError[source]

Bases: TypeError

Error raised when you pass keyword arguments into a validated function that doesn’t support them.

exception conformity.error.PositionalError[source]

Bases: TypeError

Error raised when you pass positional arguments into a validated function that doesn’t support them.

exception conformity.error.ValidationError[source]

Bases: ValueError

Error raised when a value fails to validate.

conformity.error.update_error_pointer(error: <class 'conformity.error.Error'>, pointer_or_prefix: Hashable) → <class 'conformity.error.Error'>[source]

Helper function to update an Error’s pointer attribute with a (potentially prefixed) dictionary key or list index.

class conformity.settings.Settings(data)[source]

Bases: collections.abc.Mapping, typing.Generic

Represents settings schemas and defaults that can be inherited and merged across the inheritance hierarchy.

The base classes are designed to be inherited from and have their schema extended, any number of levels deep. Multiple inheritance is also supported, with the rightmost Settings-extending base class’s schema and defaults taking precedence over all following Settings-extending base classes to the right, and so on. Schema and defaults from all base classes will be merged, with left-er base classes overriding conflicting right-er base classes’ schema or defaults components, and then finally the concrete class’s schema and settings (if any) will be merged in, overriding conflicting base classes’ schema or defaults components. This matches the behavior of Python method definition inheritance.

Examples:

class BaseSettings(Settings):
    schema = {
        'foo': fields.Integer(),
        'bar': fields.Dictionary({'baz': fields.Integer(), 'qux': fields.Boolean}),
    }  # type: SettingsSchema

    defaults = {
        'foo': 1,
        'bar': {'baz': 2},
    }  # type: SettingsData

class MoreBaseSettings(BaseSettings):
    # ``schema`` will have 'foo' and 'ipsum' from this class, 'bar' from ``BaseSettings``
    schema = {
        'foo': fields.Any(fields.Integer(), fields.Float(), fields.Decimal()),
        'ipsum': fields.UnicodeString(),
    }  # type: SettingsSchema

    # ``defaults`` will have 'ipsum' from this class, 'foo' and 'bar' from ``BaseSettings``
    defaults = {
        'ipsum': 'Default more',
    }

class OtherBaseSettings(Settings):
    schema = {
        'lorem': fields.UnicodeString(),
        'ipsum': fields.ByteString(),
    }  # type: SettingsSchema

    defaults = {
        'lorem': 'Default lorem',
    }  # type: SettingsData

class FinalSettings1(BaseSettings, OtherBaseSettings):
    # ``schema`` will have 'foo', 'bar', 'lorem', and 'ipsum'
    # ``defaults`` will have 'foo', 'bar', and 'lorem'
    pass

class FinalSettings2(OtherBaseSettings, MoreBaseSettings):
    # ``schema`` will have 'lorem', 'ipsum' from ``OtherBaseSettings``, 'foo' from ``MoreBaseSettings``, 'bar'
    # ``defaults`` will have 'lorem', 'ipsum', 'foo', 'bar'
    pass

class FinalSettings3(MoreBaseSettings, OtherBaseSettings):
    # ``schema`` will have 'foo', 'ipsum' from ``MoreBaseSettings``, 'lorem' from ``OtherBaseSettings``, 'bar'
    # ``defaults`` will have 'lorem', 'ipsum', 'foo', 'bar'
    pass

To use Settings, instantiate the target/concrete Settings subclass with the raw settings value (a Mapping, usually a dictionary), which will validate that data according to the schema, and then access the data using Mapping syntax and methods, such as settings['foo'], settings.get('foo'), 'foo' in settings, etc. The class will merge any passed values into its defaults, with passed values taking precedence over defaults when conflicts arise, before performing validation.

Settings Schema Definition

Default Values

Keys present in the dict below can be omitted from compliant settings dicts, in which case the values below will apply as the default values.

{}
exception ImproperlyConfigured[source]

Bases: Exception

Raised when validation fails for the configuration data (contents) passed into the constructor or set(data).

__contains__(key: Any) → bool[source]

Indicates whether the specific key exists in this settings data.

Parameters

key – The key to check

Returns

True if the key exists and False if it does not.

__getitem__(key: str) → Any[source]

Returns the value associated with the given key, or raises a KeyError if it does not exist.

Parameters

key – The key to look up

Returns

The value associated with the given key.

Raises

KeyError

__init__(data: Mapping[str, Any]) → None[source]

Instantiate a new Settings object and validate its contents.

Parameters

data – A mapping of unicode string keys to any values, which, together with the defined defaults in this class, should match the defined schema for this class, as merged with its parent classes.

Raises

conformity.settings.Settings.ImproperlyConfigured

__iter__() → Iterator[str][source]

Returns an iterator over the keys of this settings data.

Returns

An iterator of unicode strings.

__len__() → int[source]

Returns the number of keys in the root of this settings data.

Returns

The number of keys.

defaults = {}[source]
get(key: str, default: Optional[~_VT] = None) → Optional[~_VT][source]

Returns the value associated with the given key, or the default if specified as an argument, or None if no default is specified.

Parameters
  • key – The key to look up

  • default – The default to return if the key does not exist (which itself defaults to None)

Returns

The value associated with the given key, or the appropriate default.

items() → ItemsView[str, Any][source]

Returns an ItemsView of the settings data (even in Python 2).

Returns

A view of unicode string keys and their values in this settings data.

keys() → KeysView[str][source]

Returns a KeysView of the settings data (even in Python 2).

Returns

A view of the unicode string keys in this settings data.

schema = {}[source]
set(data: Mapping[str, Any]) → None[source]

Initialize and validate the configuration data (contents) for this settings object.

Parameters

data – A mapping of unicode string keys to any values, which, together with the defined defaults in this class, should match the defined schema for this class, as merged with its parent classes.

Raises

conformity.settings.Settings.ImproperlyConfigured

values() → ValuesView[Any][source]

Returns a ValuesView of the settings data (even in Python 2).

Returns

A view of the values in this settings data.

conformity.utils.attr_is_bool() → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is a bool.

conformity.utils.attr_is_instance_or_instance_tuple(check_type: Union[Type, Tuple[Type, ...]]) → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is a instance of or tuple of instances of the given type.

conformity.utils.attr_is_int() → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is an integer.

conformity.utils.attr_is_iterable(member_validator: Callable[[Any, Any, Any], None], iterable_validator: Union[Callable[[Any, Any, Any], None], None] = None) → Callable[[Any, Any, Any], None][source]

The equivalent of attr.validators.deep_iterable added in Attrs 19.1.0, but we still support older versions.

conformity.utils.attr_is_number() → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is a number.

conformity.utils.attr_is_set() → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is an abstract set.

conformity.utils.attr_is_string() → Callable[[Any, Any, Any], None][source]

Creates an Attrs validator that ensures the argument is a unicode string.

conformity.utils.strip_none(value: Dict[~KT, ~VT]) → Dict[~KT, ~VT][source]

Takes a dict and removes all keys that have None values, used mainly for tidying up introspection responses. Take care not to use this on something that might legitimately contain a None.

exception conformity.validator.KeywordError[source]

Bases: TypeError

Error raised when you pass keyword arguments into a validated function that doesn’t support them.

exception conformity.validator.PositionalError[source]

Bases: TypeError

Error raised when you pass positional arguments into a validated function that doesn’t support them.

exception conformity.validator.ValidationError[source]

Bases: ValueError

Error raised when a value fails to validate.

conformity.validator.validate(schema: <class 'conformity.fields.basic.Base'>, value: Any, noun: str = 'value') → None[source]

Checks the value against the schema, and raises ValidationError if validation fails.

Raises

conformity.error.ValidationError

conformity.validator.validate_call(kwargs: Union[conformity.fields.structures.Dictionary, conformity.fields.structures.SchemalessDictionary, None], returns: <class 'conformity.fields.basic.Base'>, is_method: bool = False, args: Union[conformity.fields.structures.Tuple, conformity.fields.structures.List, None] = None) → Callable[[Callable], Callable][source]

Decorator which runs validation on a callable’s arguments and its return value. Pass a schema for the kwargs and for the return value. Positional arguments are not supported unless args=fields.List(...) or args=fields.Tuple(...) is specified to supply a schema for positional arguments. In almost all cases, you should support keyword arguments, but it’s possible to support only positional arguments with kwargs=None.

Parameters
  • args – Validation schema for positional arguments, or None if positional arguments are not supported.

  • kwargs – Validation schema for keyword arguments, or None if keyword arguments are not supported.

  • returns – Validation schema for the return value

  • is_method – Set this to True for instance methods and class methods, but False (the default) for all other callables, including static methods.

Raises

conformity.error.ValidationError

conformity.validator.validate_method(kwargs: Union[conformity.fields.structures.Dictionary, conformity.fields.structures.SchemalessDictionary], returns: <class 'conformity.fields.basic.Base'>, args: Union[conformity.fields.structures.Tuple, conformity.fields.structures.List] = None) → Callable[[Callable], Callable][source]

Decorator which runs validation on a method’s arguments and its return value. Pass a schema for the kwargs and for the return value. Positional arguments are not supported unless args=fields.List(...) or args=fields.Tuple(...) is specified to supply a schema for positional arguments. In almost all cases, you should support keyword arguments, but it’s possible to support only positional arguments with kwargs=None.

Parameters
  • args – Validation schema for positional arguments, or None if positional arguments are not supported.

  • kwargs – Validation schema for keyword arguments, or None if keyword arguments are not supported.

  • returns – Validation schema for the return value

Raises

conformity.error.ValidationError

module conformity.sphinx_ext.autodoc

A set of extensions to the built-in Sphinx extensions sphinx.ext.autodoc to provide more detailed and more accurate documentation to cover the following situations:

  • Your code has type annotation comments (which autodoc does not detect) for backwards compatibility instead of using type annotation syntax (which autodoc does detect)

  • Your code has Attrs attributes with comment-based type annotations (autodoc handles Attrs attributes, only detects their type annotations if they use annotation syntax instead of annotation comments)

  • Your code uses Conformity Settings and you want to automatically document the schema and defaults (which autodoc knows nothing about)

To use this extension, add the following to your Sphinx conf.py:

extensions = [
    ...
    'sphinx.ext.autodoc',
    ...
    'conformity.sphinx_ext.autodoc',
    ...
]

There is no other configuration for this extension.

module conformity.sphinx_ext.linkcode

An extension to the built-in Spinx extension sphinx.ext.linkcode to provide a more flexible linkcode_resolve implementation that links to GitHub and includes source line number highlighting.

To use this extension, add the following to your Sphinx conf.py:

from conformity.sphinx_ext.linkcode import create_linkcode_resolve

...

extensions = [
    ...
    'sphinx.ext.linkcode',
    ...
]

...

linkcode_resolve = create_linkcode_resolve(
    'my_github_user',
    'my_project_name',
    'my_base_module',
    my_project_version_tag_string,
)
conformity.sphinx_ext.linkcode.create_linkcode_resolve(github_user: str, github_project: str, top_level_module: str, project_version_tag: str) → Callable[[str, Dict[str, Any]], str] -> Callable[[str, Dict[str, Any]], str][source]

Creates and returns an implementation of linkcode_resolve for your Sphinx conf.py file.

Parameters
  • github_user – The GitHub username as found right after the https://github.com/ in the URL

  • github_project – The GitHub project name as found right after the user name in the GitHub URL

  • top_level_module – The top-level Python module name for your project (for example: “conformity” or “pysoa”)

  • project_version_tag – The GitHub tag name for this version of your project (if you follow a common pattern, you can probably import __version__ from your project and use that)

Returns

a function that can be assigned to linkcode_resolve in your conf.py file.

Copyright © 2019 Eventbrite, freely licensed under Apache License, Version 2.0.

Documentation generated 2019 November 02 02:43 UTC.