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.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
warnings
(value: Any) → List[conformity.types.Warning][source]¶ Returns a list of warnings for the field or value.
-
-
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.
-
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.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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).-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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
, andlte
arguments.-
errors
(value: Any) → List[conformity.types.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: Optional[Union[int, float, decimal.Decimal]] = None, gte: Optional[Union[int, float, decimal.Decimal]] = None, lt: Optional[Union[int, float, decimal.Decimal]] = None, lte: Optional[Union[int, float, decimal.Decimal]] = None, description: Optional[str] = None)[source]¶ Method generated by attrs for class Integer.
-
-
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
, andlte
arguments.
-
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 thegt
,gte
,lt
, andlte
arguments.
-
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 themin_length
,max_length
, andallow_blank
arguments.-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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 themin_length
,max_length
, andallow_blank
arguments.
-
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
.-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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
-
-
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 thevalid_currencies
,gt
,gte
,lt
, andlte
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]¶ Method generated by attrs for class Amount.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
class
conformity.fields.currency.
AmountRequestDictionary
(valid_currencies: Union[Iterable[str], None] = 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 thevalid_currencies
,gt
,gte
,lt
, andlte
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: Optional[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 toFalse
makes it optionaldisplay_required – By default,
'display'
is a required field in the response, but setting this toFalse
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
, andlte
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]¶ Method generated by attrs for class AmountString.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
class
conformity.fields.email.
EmailAddress
(message: None = None, code: None = None, whitelist: Union[Iterable[str], None] = 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: Optional[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
-
domain_regex
= re.compile('((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\\Z', re.IGNORECASE)[source]¶
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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.
-
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.
-
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.
-
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]¶ Method generated by attrs for class IPv4Address.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class IPv6Address.
-
errors
(value: Any) → List[conformity.types.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
-
-
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 thatdate
with thegt
,gte
,lt
, andlte
arguments, which must also bedate
instances if specified.
-
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 thatdatetime
with thegt
,gte
,lt
, andlte
arguments, which must also bedatetime
instances if specified.
-
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 hasgt
,gte
,lt
, andlte
arguments, but they cannot be used, are deprecated, and will be removed in Conformity 2.0.0.
-
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: Optional[Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta]] = None, gte: Optional[Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta]] = None, lt: Optional[Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta]] = None, lte: Optional[Union[datetime.date, datetime.time, datetime.datetime, datetime.timedelta]] = None, description: Optional[str] = None)[source]¶ Method generated by attrs for class TemporalBase.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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 thattime
with thegt
,gte
,lt
, andlte
arguments, which must also betime
instances if specified.
-
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 thattimedelta
with thegt
,gte
,lt
, andlte
arguments, which must also betimedelta
instances if specified.
-
class
conformity.fields.structures.
AdditionalCollectionValidator
(*args, **kwds)[source]¶ Bases:
Generic
[conformity.fields.structures.VT
]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.types.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.
-
abstract
-
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 theoptional_keys
argument. No extra keys are allowed unless theallow_extra_keys
argument is set toTrue
.If the
contents
argument is an instance ofOrderedDict
, the field introspection will include adisplay_order
list of keys matching the order they exist in theOrderedDict
, and errors will be reported in the order the keys exist in theOrderedDict
. Order will be maintained for any calls toextend
as long as those calls also useOrderedDict
. 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: Optional[Mapping[Hashable, conformity.fields.basic.Base]] = None, optional_keys: Union[Tuple[Hashable, …], FrozenSet[Hashable]] = frozenset({}), allow_extra_keys: Optional[bool] = None, description: Optional[str] = None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[Mapping[Hashable, Any]]] = None)[source]¶ Method generated by attrs for class Dictionary.
-
errors
(value: Any) → List[conformity.types.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 currentDictionary
with additional contents and/or optional keys, and/or replaces theallow_extra_keys
and/ordescription
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 currentallow_extra_keys
attributedescription – If non-
None
, this overrides the currentdescription
attributereplace_optional_keys – If
True
, then theoptional_keys
argument will completely replace, instead of extend, the current optional keysadditional_validator – If non-
None
, this overrides the currentadditional_validator
attribute
- Returns
A new
Dictionary
extended from the currentDictionary
based on the supplied arguments
-
-
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]] = None)[source]¶ Method generated by attrs for class 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 thevalue_type
argument. Size of the dictionary can also be constrained with the optionalmax_length
andmin_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[Mapping[Hashable, Any]]] = None)[source]¶ Method generated by attrs for class SchemalessDictionary.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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[Sequence]] = None)[source]¶ Method generated by attrs for class Sequence.
-
-
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 themax_length
andmin_length
arguments.-
__init__
(contents, max_length=None, min_length=None, description=None, additional_validator: Optional[conformity.fields.structures.AdditionalCollectionValidator[AbstractSet]] = None)[source]¶ Method generated by attrs for class Set.
-
-
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]¶ Method generated by attrs for class Base.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class Base.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class Base.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class BooleanValidator.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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
(aTypePath
-validated string) andkwargs
(aDictionary
-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 anobject
key containing the resolved class, but this behavior can be disabled by specifyingadd_class_object_to_dict=False
to the field arguments. If you experience circular dependency errors when using this field, you can mitigate this by specifyingeager_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]¶ Method generated by attrs for class ClassConfigurationSchema.
-
errors
(value: Any) → List[conformity.types.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.
-
static
provider
(schema: Union[conformity.fields.structures.Dictionary, conformity.fields.structures.SchemalessDictionary]) → Callable[[Type], Type][source]¶
-
-
class
conformity.fields.meta.
Deprecated
(field: <class 'conformity.fields.basic.Base'>, message: str = 'This field has been deprecated')[source]¶ Bases:
conformity.fields.basic.Base
-
__init__
(field: conformity.fields.basic.Base, message: str = 'This field has been deprecated')[source]¶ Method generated by attrs for class Deprecated.
-
-
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.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class Nullable.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class ObjectInstance.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class Polymorph.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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]¶ Method generated by attrs for class PythonPath.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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 morebase_classes
.This is a special convenience
PythonPath
extension for expecting the imported item to be a type.
-
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 bybase_classes
.-
__init__
(base_classes: Optional[Union[Type, Tuple[Type, …]]] = None, description: Optional[str] = None)[source]¶ Method generated by attrs for class TypeReference.
-
errors
(value: Any) → List[conformity.types.Error][source]¶ Returns a list of errors with the value. An empty return means that it’s valid.
-
-
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 withlogging.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
- flexibledict
: This defines a mapping of logging formatter names to formatter configurations. Theformat
key specifies the log format and thedatefmt
key specifies the date format.- keys
unicode
: (no description)- values
strict
dict
: (no description)datefmt
-unicode
: The optional date format used when formatting dates in the log output (see https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).format
-unicode
: The format string for this formatter (see https://docs.python.org/3/library/logging.html#logrecord-attributes).
Optional keys:
datefmt
filters
- flexibledict
: This defines a mapping of logging filter names to filter configurations. If a config has only thename
key, thenlogging.Filter
will be instantiated with that argument. You can specify a()
key (yes, really) to override the defaultlogging.Filter
class with a custom filter implementation (which should extendlogging.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 extendinglogging.Filter
, used to override the default classlogging.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 thename
argument of thelogging.Filter
class.
Extra keys of any value are allowed. Optional keys:
()
,name
handlers
- flexibledict
: This defines a mapping of logging handler names to handler configurations. Theclass
key is the importable Python path to the class extendinglogging.Handler
. Thelevel
andfilters
keys apply to all handlers. Theformatter
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 extendinglogging.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 fromfilters
for assigning those filters to this handler.- values
unicode
: (no description)
formatter
-unicode
: A reference to a key fromformatters
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
- flexibledict
: 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 itspropagate
key is set toFalse
.- keys
unicode
: (no description)- values
strict
dict
: (no description)filters
-list
: A list of references to keys fromfilters
for assigning those filters to this logger.- values
unicode
: (no description)
handlers
-list
: A list of references to keys fromhandlers
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 toTrue
.
Optional keys:
filters
,handlers
,level
,propagate
root
- strictdict
: (no description)filters
-list
: A list of references to keys fromfilters
for assigning those filters to this logger.- values
unicode
: (no description)
handlers
-list
: A list of references to keys fromhandlers
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 toFalse
and it is rare that you should ever need to change that.disable_existing_loggers
-boolean
: Whether all existing loggers (objects obtained fromlogging.getLogger()
) should be disabled when this logging config is loaded. Take our advice and always set this toFalse
. It defaults toTrue
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.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.
-
class
conformity.error.
Error
(message, pointer=None, code: str = 'INVALID')[source]¶ Bases:
conformity.types.Issue
Represents an error found during validation of a value.
-
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.types.Error'>, pointer_or_prefix: str) → <class ‘conformity.types.Error’>[source]¶
-
class
conformity.settings.
Settings
(data)[source]¶ Bases:
Mapping
[str
,Any
]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 followingSettings
-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/concreteSettings
subclass with the raw settings value (aMapping
, usually a dictionary), which will validate that data according to the schema, and then access the data usingMapping
syntax and methods, such assettings['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 andFalse
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
-
__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.
-
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.
-
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
-
exception
-
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.
-
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.
-
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(...)
orargs=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 withkwargs=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, butFalse
(the default) for all other callables, including static methods.
- Raises
-
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] = 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(...)
orargs=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 withkwargs=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
-
module
conformity.sphinx_ext.autodoc
¶ Your code has type annotation comments (which
autodoc
does not detect) for backwards compatibility instead of using type annotation syntax (whichautodoc
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)
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:
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
¶ -
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][source]¶ Creates and returns an implementation of
linkcode_resolve
for your Sphinxconf.py
file.- Parameters
github_user – The GitHub username as found right after the
https://github.com/
in the URLgithub_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 yourconf.py
file.
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,
)
Copyright © 2023 Eventbrite, freely licensed under Apache License, Version 2.0.
Documentation generated 2023 January 10 22:12 UTC.