index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
4,991
cerberus.validator
_resolve_rules_set
null
def _resolve_rules_set(self, rules_set): if isinstance(rules_set, Mapping): return rules_set elif isinstance(rules_set, _str_type): return self.rules_set_registry.get(rules_set) return None
(self, rules_set)
4,992
cerberus.validator
_resolve_schema
null
def _resolve_schema(self, schema): if isinstance(schema, Mapping): return schema elif isinstance(schema, _str_type): return self.schema_registry.get(schema) return None
(self, schema)
4,993
cerberus.validator
_validate_allof
{'type': 'list', 'logical': 'allof'}
def _validate_allof(self, definitions, field, value): """{'type': 'list', 'logical': 'allof'}""" valids, _errors = self.__validate_logical('allof', definitions, field, value) if valids < len(definitions): self._error(field, errors.ALLOF, _errors, valids, len(definitions))
(self, definitions, field, value)
4,994
cerberus.validator
dummy
{'oneof': [{'type': 'boolean'}, {'type': ['dict', 'string'], 'check_with': 'bulk_schema'}]}
def dummy_for_rule_validation(rule_constraints): def dummy(self, constraint, field, value): raise RuntimeError( 'Dummy method called. Its purpose is to hold just' 'validation constraints for a rule in its ' 'docstring.' ) f = dummy f.__doc__ = rule_constr...
(self, constraint, field, value)
4,995
cerberus.validator
_validate_allowed
{'type': 'container'}
def _validate_allowed(self, allowed_values, field, value): """{'type': 'container'}""" if isinstance(value, Iterable) and not isinstance(value, _str_type): unallowed = tuple(x for x in value if x not in allowed_values) if unallowed: self._error(field, errors.UNALLOWED_VALUES, unallow...
(self, allowed_values, field, value)
4,996
cerberus.validator
_validate_anyof
{'type': 'list', 'logical': 'anyof'}
def _validate_anyof(self, definitions, field, value): """{'type': 'list', 'logical': 'anyof'}""" valids, _errors = self.__validate_logical('anyof', definitions, field, value) if valids < 1: self._error(field, errors.ANYOF, _errors, valids, len(definitions))
(self, definitions, field, value)
4,997
cerberus.validator
_validate_check_with
{'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]}
def _validate_check_with(self, checks, field, value): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if isinstance(checks, _str_type): ...
(self, checks, field, value)
4,998
cerberus.validator
_validate_contains
{'empty': False }
def _validate_contains(self, expected_values, field, value): """{'empty': False }""" if not isinstance(value, Iterable): return if not isinstance(expected_values, Iterable) or isinstance( expected_values, _str_type ): expected_values = set((expected_values,)) else: ex...
(self, expected_values, field, value)
4,999
cerberus.validator
_validate_dependencies
{'type': ('dict', 'hashable', 'list'), 'check_with': 'dependencies'}
def _validate_dependencies(self, dependencies, field, value): """{'type': ('dict', 'hashable', 'list'), 'check_with': 'dependencies'}""" if isinstance(dependencies, _str_type) or not isinstance( dependencies, (Iterable, Mapping) ): dependencies = (dependencies,) if isinstance(dependencie...
(self, dependencies, field, value)
5,000
cerberus.validator
_validate_empty
{'type': 'boolean'}
def _validate_empty(self, empty, field, value): """{'type': 'boolean'}""" if isinstance(value, Sized) and len(value) == 0: self._drop_remaining_rules( 'allowed', 'forbidden', 'items', 'minlength', 'maxlength', 'regex', '...
(self, empty, field, value)
5,001
cerberus.validator
_validate_excludes
{'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}}
def _validate_excludes(self, excluded_fields, field, value): """{'type': ('hashable', 'list'), 'schema': {'type': 'hashable'}}""" if isinstance(excluded_fields, Hashable): excluded_fields = [excluded_fields] # Mark the currently evaluated field as not required for now if it actually is. # One of...
(self, excluded_fields, field, value)
5,002
cerberus.validator
_validate_forbidden
{'type': 'list'}
def _validate_forbidden(self, forbidden_values, field, value): """{'type': 'list'}""" if isinstance(value, Sequence) and not isinstance(value, _str_type): forbidden = set(value) & set(forbidden_values) if forbidden: self._error(field, errors.FORBIDDEN_VALUES, list(forbidden)) els...
(self, forbidden_values, field, value)
5,003
cerberus.validator
_validate_items
{'type': 'list', 'check_with': 'items'}
def _validate_items(self, items, field, values): """{'type': 'list', 'check_with': 'items'}""" if len(items) != len(values): self._error(field, errors.ITEMS_LENGTH, len(items), len(values)) else: schema = dict( (i, definition) for i, definition in enumerate(items) ) # no...
(self, items, field, values)
5,004
cerberus.validator
_validate_keysrules
{'type': ['dict', 'string'], 'check_with': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']}
def _validate_keysrules(self, schema, field, value): """ {'type': ['dict', 'string'], 'check_with': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ if isinstance(value, Mapping): validator = self._get_child_validator( document_crumb=field, schema_c...
(self, schema, field, value)
5,005
cerberus.validator
_validate_max
{'nullable': False }
def _validate_max(self, max_value, field, value): """{'nullable': False }""" try: if value > max_value: self._error(field, errors.MAX_VALUE) except TypeError: pass
(self, max_value, field, value)
5,006
cerberus.validator
_validate_maxlength
{'type': 'integer'}
def _validate_maxlength(self, max_length, field, value): """{'type': 'integer'}""" if isinstance(value, Iterable) and len(value) > max_length: self._error(field, errors.MAX_LENGTH, len(value))
(self, max_length, field, value)
5,007
cerberus.validator
dummy
def dummy_for_rule_validation(rule_constraints): def dummy(self, constraint, field, value): raise RuntimeError( 'Dummy method called. Its purpose is to hold just' 'validation constraints for a rule in its ' 'docstring.' ) f = dummy f.__doc__ = rule_constr...
(self, constraint, field, value)
5,008
cerberus.validator
_validate_min
{'nullable': False }
def _validate_min(self, min_value, field, value): """{'nullable': False }""" try: if value < min_value: self._error(field, errors.MIN_VALUE) except TypeError: pass
(self, min_value, field, value)
5,009
cerberus.validator
_validate_minlength
{'type': 'integer'}
def _validate_minlength(self, min_length, field, value): """{'type': 'integer'}""" if isinstance(value, Iterable) and len(value) < min_length: self._error(field, errors.MIN_LENGTH, len(value))
(self, min_length, field, value)
5,010
cerberus.validator
_validate_noneof
{'type': 'list', 'logical': 'noneof'}
def _validate_noneof(self, definitions, field, value): """{'type': 'list', 'logical': 'noneof'}""" valids, _errors = self.__validate_logical('noneof', definitions, field, value) if valids > 0: self._error(field, errors.NONEOF, _errors, valids, len(definitions))
(self, definitions, field, value)
5,011
cerberus.validator
_validate_nullable
{'type': 'boolean'}
def _validate_nullable(self, nullable, field, value): """{'type': 'boolean'}""" if value is None: if not nullable: self._error(field, errors.NOT_NULLABLE) self._drop_remaining_rules( "allof", 'allowed', "anyof", 'empty', 'fo...
(self, nullable, field, value)
5,012
cerberus.validator
_validate_oneof
{'type': 'list', 'logical': 'oneof'}
def _validate_oneof(self, definitions, field, value): """{'type': 'list', 'logical': 'oneof'}""" valids, _errors = self.__validate_logical('oneof', definitions, field, value) if valids != 1: self._error(field, errors.ONEOF, _errors, valids, len(definitions))
(self, definitions, field, value)
5,013
cerberus.validator
_validate_readonly
{'type': 'boolean'}
def _validate_readonly(self, readonly, field, value): """{'type': 'boolean'}""" if readonly: if not self._is_normalized: self._error(field, errors.READONLY_FIELD) # If the document was normalized (and therefore already been # checked for readonly fields), we still have to ret...
(self, readonly, field, value)
5,014
cerberus.validator
_validate_regex
{'type': 'string'}
def _validate_regex(self, pattern, field, value): """{'type': 'string'}""" if not isinstance(value, _str_type): return if not pattern.endswith('$'): pattern += '$' re_obj = re.compile(pattern) if not re_obj.match(value): self._error(field, errors.REGEX_MISMATCH)
(self, pattern, field, value)
5,015
cerberus.validator
dummy
{'type': 'boolean'}
def dummy_for_rule_validation(rule_constraints): def dummy(self, constraint, field, value): raise RuntimeError( 'Dummy method called. Its purpose is to hold just' 'validation constraints for a rule in its ' 'docstring.' ) f = dummy f.__doc__ = rule_constr...
(self, constraint, field, value)
5,017
cerberus.validator
_validate_schema
{'type': ['dict', 'string'], 'anyof': [{'check_with': 'schema'}, {'check_with': 'bulk_schema'}]}
def _validate_schema(self, schema, field, value): """ {'type': ['dict', 'string'], 'anyof': [{'check_with': 'schema'}, {'check_with': 'bulk_schema'}]} """ if schema is None: return if isinstance(value, Sequence) and not isinstance(value, _str_type): self.__validat...
(self, schema, field, value)
5,018
cerberus.validator
_validate_type
{'type': ['string', 'list'], 'check_with': 'type'}
def _validate_type(self, data_type, field, value): """ {'type': ['string', 'list'], 'check_with': 'type'} """ if not data_type: return types = (data_type,) if isinstance(data_type, _str_type) else data_type for _type in types: # TODO remove this block on next major release ...
(self, data_type, field, value)
5,019
cerberus.validator
_validate_valuesrules
{'type': ['dict', 'string'], 'check_with': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']}
def _validate_valuesrules(self, schema, field, value): """ {'type': ['dict', 'string'], 'check_with': 'bulk_schema', 'forbidden': ['rename', 'rename_handler']} """ schema_crumb = (field, 'valuesrules') if isinstance(value, Mapping): validator = self._get_child_validator( ...
(self, schema, field, value)
5,020
cerberus.validator
normalized
Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have...
def normalized(self, document, schema=None, always_return_document=False): """ Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. ...
(self, document, schema=None, always_return_document=False)
5,022
cerberus.validator
validated
Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed.
def validated(self, *args, **kwargs): """ Wrapper around :meth:`~cerberus.Validator.validate` that returns the normalized and validated document or :obj:`None` if validation failed. """ always_return_document = kwargs.pop('always_return_document', False) self.validate(*args, **kwargs) if sel...
(self, *args, **kwargs)
5,029
jsii._runtime
JSIIAbstractClass
null
class JSIIAbstractClass(abc.ABCMeta, JSIIMeta): pass
(name, bases, namespace, **kwargs)
5,030
jsii._runtime
__call__
null
def __call__(cls: Type[M], *args: Any, **kwargs) -> M: # There is no way to constrain the metaclass of a `Type[M]` hint today, so we have to # perform a `cast` trick here in order for MyPy to accept this code as valid... The implicit # arguments to `super()` otherwise are `super(__class__, cls)`, which resu...
(cls: Type[~M], *args: Any, **kwargs) -> ~M
5,031
abc
__instancecheck__
Override for isinstance(instance, cls).
def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" return _abc_instancecheck(cls, instance)
(cls, instance)
5,032
abc
__new__
null
def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) _abc_init(cls) return cls
(mcls, name, bases, namespace, **kwargs)
5,033
jsii.python
__setattr__
null
def __setattr__(self, key: str, value: Any) -> None: obj = getattr(self, key, None) if isinstance(obj, _ClassProperty): return obj.__set__(self, value) return super().__setattr__(key, value)
(self, key: str, value: Any) -> NoneType
5,034
abc
__subclasscheck__
Override for issubclass(subclass, cls).
def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" return _abc_subclasscheck(cls, subclass)
(cls, subclass)
5,035
abc
_abc_caches_clear
Clear the caches (for debugging or testing).
def _abc_caches_clear(cls): """Clear the caches (for debugging or testing).""" _reset_caches(cls)
(cls)
5,036
abc
_abc_registry_clear
Clear the registry (for debugging or testing).
def _abc_registry_clear(cls): """Clear the registry (for debugging or testing).""" _reset_registry(cls)
(cls)
5,037
abc
_dump_registry
Debug helper to print the ABC registry.
def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file) print(f"Inv. counter: {get_cache_token()}", file=file) (_abc_registry, _abc_cache, _abc_negative_cache, _abc_negative_cache_version) = _get_dump(cls) ...
(cls, file=None)
5,038
abc
register
Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator.
def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ return _abc_register(cls, subclass)
(cls, subclass)
5,039
jsii._runtime
JSIIAssembly
null
class JSIIAssembly: name: str version: str module: str filename: str @classmethod def load(cls, *args, _kernel=kernel, **kwargs) -> "JSIIAssembly": # Our object here really just acts as a record for our JSIIAssembly, it doesn't # offer any functionality itself, besides this clas...
(name: str, version: str, module: str, filename: str) -> None
5,040
attr._make
_frozen_delattrs
Attached to frozen classes as __delattr__.
def _frozen_delattrs(self, name): """ Attached to frozen classes as __delattr__. """ raise FrozenInstanceError()
(self, name)
5,041
jsii._runtime
__eq__
Method generated by attrs for class JSIIAssembly.
import abc import os import sys import subprocess import attr from typing import ( Any, Callable, cast, List, Mapping, Optional, Sequence, Type, TypeVar, ) from . import _reference_map from ._compat import importlib_resources from ._kernel import Kernel from .python import _ClassP...
(self, other)
5,042
jsii._runtime
__ge__
Method generated by attrs for class JSIIAssembly.
null
(self, other)
5,043
attr._make
slots_getstate
Automatically created by attrs.
def _make_getstate_setstate(self): """ Create custom __setstate__ and __getstate__ methods. """ # __weakref__ is not writable. state_attr_names = tuple( an for an in self._attr_names if an != "__weakref__" ) def slots_getstate(self): """ Automatically created by attrs...
(self)
5,051
attr._make
_frozen_setattrs
Attached to frozen classes as __setattr__.
def _frozen_setattrs(self, name, value): """ Attached to frozen classes as __setattr__. """ if isinstance(self, BaseException) and name in ( "__cause__", "__context__", "__traceback__", ): BaseException.__setattr__(self, name, value) return raise FrozenIn...
(self, name, value)
5,053
jsii._runtime
JSIIMeta
null
class JSIIMeta(_ClassPropertyMeta, type): def __new__( cls: Type["JSIIMeta"], name: str, bases: tuple, attrs: dict, *, jsii_type: Optional[str] = None, ) -> "JSIIMeta": # We want to ensure that subclasses of a JSII class do not require setting the ...
(name: str, bases: tuple, attrs: dict, *, jsii_type: Optional[str] = None) -> 'JSIIMeta'
5,055
jsii._runtime
__new__
null
def __new__( cls: Type["JSIIMeta"], name: str, bases: tuple, attrs: dict, *, jsii_type: Optional[str] = None, ) -> "JSIIMeta": # We want to ensure that subclasses of a JSII class do not require setting the # jsii_type keyword argument. They should be able to subclass it as normal. # ...
(cls: Type[jsii._runtime.JSIIMeta], name: str, bases: tuple, attrs: dict, *, jsii_type: Optional[str] = None) -> jsii._runtime.JSIIMeta
5,064
jsii._runtime
data_type
null
def data_type( *, jsii_type: str, jsii_struct_bases: List[Type[Any]], name_mapping: Mapping[str, str], ) -> Callable[[T], T]: def deco(cls): cls.__jsii_type__ = jsii_type cls.__jsii_struct_bases__ = jsii_struct_bases cls.__jsii_name_mapping__ = name_mapping _reference...
(*, jsii_type: str, jsii_struct_bases: List[Type[Any]], name_mapping: Mapping[str, str]) -> Callable[[~T], ~T]
5,065
jsii._runtime
enum
null
def enum(*, jsii_type: str) -> Callable[[T], T]: def deco(cls): cls.__jsii_type__ = jsii_type _reference_map.register_enum(cls) return cls return deco
(*, jsii_type: str) -> Callable[[~T], ~T]
5,067
jsii._runtime
implements
null
def implements(*interfaces: Type[Any]) -> Callable[[T], T]: def deco(cls): cls.__jsii_type__ = getattr(cls, "__jsii_type__", None) cls.__jsii_ifaces__ = getattr(cls, "__jsii_ifaces__", []) + list(interfaces) return cls return deco
(*interfaces: Type[Any]) -> Callable[[~T], ~T]
5,068
jsii._runtime
interface
null
def interface(*, jsii_type: str) -> Callable[[T], T]: def deco(iface): iface.__jsii_type__ = jsii_type _reference_map.register_interface(iface) return iface return deco
(*, jsii_type: str) -> Callable[[~T], ~T]
5,069
jsii._runtime
member
null
def member(*, jsii_name: str) -> Callable[[F], F]: def deco(fn): fn.__jsii_name__ = jsii_name return fn return deco
(*, jsii_name: str) -> Callable[[~F], ~F]
5,070
jsii._runtime
proxy_for
null
def proxy_for(abstract_class: Type[Any]) -> Type[Any]: if not hasattr(abstract_class, "__jsii_proxy_class__"): raise TypeError(f"{abstract_class} is not a JSII Abstract class.") return cast(Any, abstract_class).__jsii_proxy_class__()
(abstract_class: Type[Any]) -> Type[Any]
5,073
collections.abc
ItemsView
null
from collections.abc import ItemsView
(mapping)
5,092
collections.abc
_hash
Compute the hash value of a set. Note that we don't define __hash__: not all sets are hashable. But if you define a hashable set type, its __hash__ should call this function. This must be compatible __eq__. All sets ought to compare equal if they contain the same eleme...
null
(self)
5,093
collections.abc
isdisjoint
Return True if two sets have a null intersection.
null
(self, other)
5,094
collections.abc
KeysView
null
from collections.abc import KeysView
(mapping)
5,115
serpent
Serializer
Serialize an object tree to a byte stream. It is not thread-safe: make sure you're not making changes to the object tree that is being serialized, and don't use the same serializer across different threads.
class Serializer(object): """ Serialize an object tree to a byte stream. It is not thread-safe: make sure you're not making changes to the object tree that is being serialized, and don't use the same serializer across different threads. """ dispatch = {} def __init__(self, indent=False,...
(indent=False, module_in_classname=False, bytes_repr=False)
5,116
serpent
__init__
Initialize the serializer. indent=indent the output over multiple lines (default=false) module_in_classname = include module prefix for class names or only use the class name itself bytes_repr = should the bytes literal value representation be used instead of base-64 encoding for bytes ...
def __init__(self, indent=False, module_in_classname=False, bytes_repr=False): """ Initialize the serializer. indent=indent the output over multiple lines (default=false) module_in_classname = include module prefix for class names or only use the class name itself bytes_repr = should the bytes liter...
(self, indent=False, module_in_classname=False, bytes_repr=False)
5,117
serpent
_check_hashable_type
null
def _check_hashable_type(self, t): if t not in (bool, bytes, str, tuple) and not issubclass(t, numbers.Number): if issubclass(t, enum.Enum): return raise TypeError("one of the keys in a dict or set is not of a primitive hashable type: " + str(t) + ". Use simple ty...
(self, t)
5,118
serpent
_serialize
null
def _serialize(self, obj, out, level): if level > self.maximum_level: raise ValueError( "Object graph nesting too deep. Increase serializer.maximum_level if you think you need more, " " but this may cause a RecursionError instead if Python's recursion limit doesn't allow it.") t ...
(self, obj, out, level)
5,119
serpent
get_class_name
null
def get_class_name(self, obj): if self.module_in_classname: return "%s.%s" % (obj.__class__.__module__, obj.__class__.__name__) else: return obj.__class__.__name__
(self, obj)
5,120
serpent
ser_array_array
null
def ser_array_array(self, array_obj, out, level): if array_obj.typecode == 'u': self._serialize(array_obj.tounicode(), out, level) else: self._serialize(array_obj.tolist(), out, level)
(self, array_obj, out, level)
5,121
serpent
ser_builtins_complex
null
def ser_builtins_complex(self, complex_obj, out, level): out.append("(") self.ser_builtins_float(complex_obj.real, out, level) if complex_obj.imag >= 0: out.append("+") self.ser_builtins_float(complex_obj.imag, out, level) out.append("j)")
(self, complex_obj, out, level)
5,122
serpent
ser_builtins_dict
null
def ser_builtins_dict(self, dict_obj, out, level): if id(dict_obj) in self.serialized_obj_ids: raise ValueError("Circular reference detected (dict)") self.serialized_obj_ids.add(id(dict_obj)) append = out.append serialize = self._serialize if self.indent and dict_obj: indent_chars = ...
(self, dict_obj, out, level)
5,123
serpent
ser_builtins_float
null
def ser_builtins_float(self, float_obj, out, level): if math.isnan(float_obj): # there's no literal expression for a float NaN... out.append("{'__class__':'float','value':'nan'}") elif math.isinf(float_obj): # output a literal expression that overflows the float and results in +/-INF ...
(self, float_obj, out, level)
5,124
serpent
ser_builtins_frozenset
null
def ser_builtins_frozenset(self, set_obj, out, level): self.ser_builtins_set(set_obj, out, level)
(self, set_obj, out, level)
5,125
serpent
ser_builtins_list
null
def ser_builtins_list(self, list_obj, out, level): if id(list_obj) in self.serialized_obj_ids: raise ValueError("Circular reference detected (list)") self.serialized_obj_ids.add(id(list_obj)) append = out.append serialize = self._serialize if self.indent and list_obj: indent_chars = ...
(self, list_obj, out, level)
5,126
serpent
ser_builtins_set
null
def ser_builtins_set(self, set_obj, out, level): append = out.append serialize = self._serialize if self.indent and set_obj: indent_chars = " " * level indent_chars_inside = indent_chars + " " append("{\n") try: sorted_elts = sorted(set_obj) except TypeE...
(self, set_obj, out, level)
5,127
serpent
ser_builtins_tuple
null
def ser_builtins_tuple(self, tuple_obj, out, level): append = out.append serialize = self._serialize if self.indent and tuple_obj: indent_chars = " " * level indent_chars_inside = indent_chars + " " append("(\n") for elt in tuple_obj: append(indent_chars_inside)...
(self, tuple_obj, out, level)
5,128
serpent
ser_datetime_date
null
def ser_datetime_date(self, date_obj, out, level): out.append(repr(date_obj.isoformat()))
(self, date_obj, out, level)
5,129
serpent
ser_datetime_datetime
null
def ser_datetime_datetime(self, datetime_obj, out, level): out.append(repr(datetime_obj.isoformat()))
(self, datetime_obj, out, level)
5,130
serpent
ser_datetime_time
null
def ser_datetime_time(self, time_obj, out, level): out.append(repr(str(time_obj)))
(self, time_obj, out, level)
5,131
serpent
ser_datetime_timedelta
null
def ser_datetime_timedelta(self, timedelta_obj, out, level): secs = timedelta_obj.total_seconds() out.append(repr(secs))
(self, timedelta_obj, out, level)
5,132
serpent
ser_decimal_Decimal
null
def ser_decimal_Decimal(self, decimal_obj, out, level): # decimal is serialized as a string to avoid losing precision out.append(repr(str(decimal_obj)))
(self, decimal_obj, out, level)
5,133
serpent
ser_default_class
null
def ser_default_class(self, obj, out, level): if id(obj) in self.serialized_obj_ids: raise ValueError("Circular reference detected (class)") self.serialized_obj_ids.add(id(obj)) try: # note: python 3.11+ object itself now has __getstate__ has_own_getstate = ( hasattr(type...
(self, obj, out, level)
5,134
serpent
ser_exception_class
null
def ser_exception_class(self, exc_obj, out, level): value = { "__class__": self.get_class_name(exc_obj), "__exception__": True, "args": exc_obj.args, "attributes": vars(exc_obj) # add any custom attributes } self._serialize(value, out, level)
(self, exc_obj, out, level)
5,135
serpent
ser_uuid_UUID
null
def ser_uuid_UUID(self, uuid_obj, out, level): out.append(repr(str(uuid_obj)))
(self, uuid_obj, out, level)
5,136
serpent
serialize
Serialize the object tree to bytes.
def serialize(self, obj): """Serialize the object tree to bytes.""" self.special_classes_registry_copy = _special_classes_registry.copy() # make it thread safe header = "# serpent utf-8 python3.2\n" out = [header] try: gc.disable() self.serialized_obj_ids = set() self._seria...
(self, obj)
5,137
collections.abc
ValuesView
null
from collections.abc import ValuesView
(mapping)
5,143
serpent
_reset_special_classes_registry
null
def _reset_special_classes_registry(): _special_classes_registry.clear() _special_classes_registry[KeysView] = _ser_DictView _special_classes_registry[ValuesView] = _ser_DictView _special_classes_registry[ItemsView] = _ser_DictView _special_classes_registry[collections.OrderedDict] = _ser_OrderedDic...
()
5,144
serpent
_ser_DictView
null
def _ser_DictView(obj, serializer, outputstream, indentlevel): serializer.ser_builtins_list(obj, outputstream, indentlevel)
(obj, serializer, outputstream, indentlevel)
5,145
serpent
_ser_OrderedDict
null
def _ser_OrderedDict(obj, serializer, outputstream, indentlevel): obj = { "__class__": "collections.OrderedDict" if serializer.module_in_classname else "OrderedDict", "items": list(obj.items()) } serializer._serialize(obj, outputstream, indentlevel)
(obj, serializer, outputstream, indentlevel)
5,146
serpent
_translate_byte_type
null
def _translate_byte_type(t, data, bytes_repr): if bytes_repr: if t == bytes: return repr(data) elif t == bytearray: return repr(bytes(data)) elif t == memoryview: return repr(bytes(data)) else: raise TypeError("invalid bytes type") ...
(t, data, bytes_repr)
5,154
serpent
dump
Serialize object tree to a file. indent = indent the output over multiple lines (default=false) module_in_classname = include module prefix for class names or only use the class name itself bytes_repr = should the bytes literal value representation be used instead of base-64 encoding for bytes types? ...
def dump(obj, file, indent=False, module_in_classname=False, bytes_repr=False): """ Serialize object tree to a file. indent = indent the output over multiple lines (default=false) module_in_classname = include module prefix for class names or only use the class name itself bytes_repr = should the by...
(obj, file, indent=False, module_in_classname=False, bytes_repr=False)
5,155
serpent
dumps
Serialize object tree to bytes. indent = indent the output over multiple lines (default=false) module_in_classname = include module prefix for class names or only use the class name itself bytes_repr = should the bytes literal value representation be used instead of base-64 encoding for bytes types? ...
def dumps(obj, indent=False, module_in_classname=False, bytes_repr=False): """ Serialize object tree to bytes. indent = indent the output over multiple lines (default=false) module_in_classname = include module prefix for class names or only use the class name itself bytes_repr = should the bytes li...
(obj, indent=False, module_in_classname=False, bytes_repr=False)
5,158
serpent
load
Deserialize bytes from a file back to object tree. Uses ast.literal_eval (safe).
def load(file): """Deserialize bytes from a file back to object tree. Uses ast.literal_eval (safe).""" data = file.read() return loads(data)
(file)
5,159
serpent
loads
Deserialize bytes back to object tree. Uses ast.literal_eval (safe).
def loads(serialized_bytes): """Deserialize bytes back to object tree. Uses ast.literal_eval (safe).""" serialized = codecs.decode(serialized_bytes, "utf-8") if '\x00' in serialized: raise ValueError( "The serpent data contains 0-bytes so it cannot be parsed by ast.literal_eval. Has it b...
(serialized_bytes)
5,162
serpent
register_class
Register a special serializer function for objects of the given class. The function will be called with (object, serpent_serializer, outputstream, indentlevel) arguments. The function must write the serialized data to outputstream. It doesn't return a value.
def register_class(clazz, serializer): """ Register a special serializer function for objects of the given class. The function will be called with (object, serpent_serializer, outputstream, indentlevel) arguments. The function must write the serialized data to outputstream. It doesn't return a value. ...
(clazz, serializer)
5,164
serpent
tobytes
Utility function to convert obj back to actual bytes if it is a serpent-encoded bytes dictionary (a dict with base-64 encoded 'data' in it and 'encoding'='base64'). If obj is already bytes or a byte-like type, return obj unmodified. Will raise TypeError if obj is none of the above. All this is not...
def tobytes(obj): """ Utility function to convert obj back to actual bytes if it is a serpent-encoded bytes dictionary (a dict with base-64 encoded 'data' in it and 'encoding'='base64'). If obj is already bytes or a byte-like type, return obj unmodified. Will raise TypeError if obj is none of the ab...
(obj)
5,165
serpent
unregister_class
Unregister the specialcase serializer for the given class.
def unregister_class(clazz): """Unregister the specialcase serializer for the given class.""" if clazz in _special_classes_registry: del _special_classes_registry[clazz]
(clazz)
5,167
releases
BulletListVisitor
null
class BulletListVisitor(nodes.NodeVisitor): def __init__(self, document, app, docnames, is_singlepage): nodes.NodeVisitor.__init__(self, document) self.found_changelog = False self.app = app # document names to seek out (eg "changelog") self.docnames = docnames self.i...
(document, app, docnames, is_singlepage)
5,168
releases
__init__
null
def __init__(self, document, app, docnames, is_singlepage): nodes.NodeVisitor.__init__(self, document) self.found_changelog = False self.app = app # document names to seek out (eg "changelog") self.docnames = docnames self.is_singlepage = is_singlepage
(self, document, app, docnames, is_singlepage)
5,169
docutils.nodes
dispatch_departure
Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure.
def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure)...
(self, node)
5,170
docutils.nodes
dispatch_visit
Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit.
def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.docum...
(self, node)
5,171
docutils.nodes
unknown_departure
Called before exiting unknown `Node` types. Raise exception unless overridden.
def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (self.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type...
(self, node)
5,172
releases
unknown_visit
null
def unknown_visit(self, node): pass
(self, node)
5,173
releases
visit_bullet_list
null
def visit_bullet_list(self, node): # Short circuit if already mutated a changelog bullet list or if the # one being visited doesn't appear to apply. if self.found_changelog: return # Also short circuit if we're in singlepage mode and the node's parent # doesn't seem to be named after an expe...
(self, node)
5,174
releases.models
Issue
null
class Issue(nodes.Element): # Technically, we just need number, but heck, you never know... _cmp_keys = ("type", "number", "backported", "major") @property def type(self): return self["type_"] @property def is_featurelike(self): if self.type == "bug": return self.ma...
(rawsource='', *children, **attributes)