code stringlengths 1 18.2k |
|---|
case of success. Otherwise, raises a ValidationError """ # backwards compatibility instance_of = instance_of or (kw_context_args.pop('allowed_types') if 'allowed_types' in kw_context_args else None) is_in = is_in or (kw_context_args.pop('allowed_values') if 'allowed_values' in kw_context_args else None) try: # the foll... |
try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ? # > maybe not because quite dangerous (AST mod) and below we skip the "return True" everywhere for performance # # Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically # > but th... |
MissingMandatoryParameterException('Error, ' + name + '" is mandatory, it should be non-None') # else do nothing and return else: if equals is not None: if value != equals: raise NotEqual(wrong_value=value, ref_value=equals) if instance_of is not None: assert_instance_of(value, instance_of) if subclass_of is not None: ... |
NotInAllowedValues(wrong_value=value, allowed_values=is_in) if contains is not None: # inlined version of contains(ref_value=contains)(value) without 'return True' if contains not in value: raise DoesNotContainValue(wrong_value=value, ref_value=contains) if subset_of is not None: # inlined version of is_subset(referenc... |
0: raise NotSuperset(wrong_value=value, reference_set=superset_of, missing=missing) if min_value is not None: # inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True' if min_strict: if not value > min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=True) else: if... |
strict=True) else: if not value <= max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=False) if length is not None: # inlined version of has_length() without 'return True' if len(value) != length: raise WrongLength(wrong_value=value, ref_length=length) if min_len is not None: # inlined version of mi... |
min_length=min_len, strict=False) if max_len is not None: # inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True' if max_len_strict: if not len(value) < max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=True) else: if not len(value) <= max_len: raise TooLon... |
**kw_context_args) else: # basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args if error_type is None and help_msg is None and len(kw_context_args) > 0: raise ValueError("Keyword context arguments have been provided but help_msg and error_type are not: {}" "".fo... |
def gt(min_value, # type: Any strict=False # type: bool ): """ 'Greater than' validation_function generator. Returns a validation_function to check that x >= min_value (strict=False, default) or x > min_value (strict=True) :param min_value: minimum value for x :param strict: Boolean flag to switch between x >= min_valu... |
True else: # raise Failure('x > ' + str(min_value) + ' does not hold for x=' + str(x)) # '{val} is not strictly greater than {ref}' raise TooSmall(wrong_value=x, min_value=min_value, strict=True) else: def gt_(x): if x >= min_value: return True else: # raise Failure('x >= ' + str(min_value) + ' does not hold for x=' + ... |
TooSmall(wrong_value=x, min_value=min_value, strict=False) gt_.__name__ = '{}greater_than_{}'.format('strictly_' if strict else '', min_value) return gt_ |
def lt(max_value, # type: Any strict=False # type: bool ): """ 'Lesser than' validation_function generator. Returns a validation_function to check that x <= max_value (strict=False, default) or x < max_value (strict=True) :param max_value: maximum value for x :param strict: Boolean flag to switch between x <= max_value... |
True else: # raise Failure('x < ' + str(max_value) + ' does not hold for x=' + str(x)) # '{val} is not strictly lesser than {ref}' raise TooBig(wrong_value=x, max_value=max_value, strict=True) else: def lt_(x): if x <= max_value: return True else: # raise Failure('x <= ' + str(max_value) + ' does not hold for x=' + str... |
TooBig(wrong_value=x, max_value=max_value, strict=False) lt_.__name__ = '{}lesser_than_{}'.format('strictly_' if strict else '', max_value) return lt_ |
def between(min_val, # type: Any max_val, # type: Any open_left=False, # type: bool open_right=False # type: bool ): """ 'Is between' validation_function generator. Returns a validation_function to check that min_val <= x <= max_val (default). open_right and open_left flags allow to transform each side into strict mode... |
:param max_val: maximum value for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: """ if open_left and open_right: def between_(x): if (min_val < x) and (x < max_val): return True else: # raise Failure('{} <... |
NotInRange(wrong_value=x, min_value=min_val, left_strict=True, max_value=max_val, right_strict=True) elif open_left: def between_(x): if (min_val < x) and (x <= max_val): return True else: # raise Failure('between: {} < x <= {} does not hold for x={}'.format(min_val, max_val, x)) raise NotInRange(wrong_value=x, min_val... |
does not hold for x={}'.format(min_val, max_val, x)) raise NotInRange(wrong_value=x, min_value=min_val, left_strict=False, max_value=max_val, right_strict=True) else: def between_(x): if (min_val <= x) and (x <= max_val): return True else: # raise Failure('between: {} <= x <= {} does not hold for x={}'.format(min_val, ... |
def _sub_process_main(started_event: Event, channel_name: str, connection: Connection, consumer_configuration: BrightsideConsumerConfiguration, consumer_factory: Callable[[Connection, BrightsideConsumerConfiguration, logging.Logger], BrightsideConsumer], command_processor_factory: Callable[[str], CommandProcessor], map... |
The data should be value types, not reference types as we will receive a copy of the original. Inter-process communication is signalled by the event - to indicate startup - and the pipeline to facilitate a sentinel or stop message :param started_event: Used by the sub-process to signal that it is ready :param channel_n... |
broker for identification :param connection: The 'broker' connection :param consumer_configuration: How to configure our consumer of messages from the channel :param consumer_factory: Callback to create the consumer. User code as we don't know what consumer library they want to use. Arame? Something else? :param comman... |
requests and handlers :param mapper_func: We need to map between messages on the wire and our handlers :return: """ logger = logging.getLogger(__name__) consumer = consumer_factory(connection, consumer_configuration, logger) channel = Channel(name=channel_name, consumer=consumer, pipeline=consumer_configuration.pipelin... |
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script o... |
) with context.begin_transaction(): context.run_migrations() |
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ app_conf = dci_config.generate_conf() connectable = dci_config.get_engine(app_conf) with connectable.connect() as connection: context.configure( connection=conne... |
def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ('Could not verify your access level for that URL.' 'Please login with proper credentials.') auth_message = json.dumps({'_status': 'Unauthorized', 'message': auth_message}) headers = {'WWW-Authenticate': 'Basic realm="Login required... |
def modify(self, **kwargs): """Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countryco... |
* countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Defa... |
if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser', 'name']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of <PingdomContact>.modify()\n') response = self.pingdom.request('PUT', 'notification_contacts/%s' % self.id, kwargs) return res... |
def _establish_connection(self, conn: BrokerConnection) -> None: """ We don't use a pool here. We only have one consumer connection per process, so we get no value from a pool, and we want to use a heartbeat to keep the consumer collection alive, which does not work with a pool :return: the connection to the transport ... |
%s', conn.as_uri()) except kombu_exceptions.OperationalError as oe: self._logger.error("Error connecting to RMQ, could not retry %s", oe) # Try to clean up the mess if self._conn is not None: self._conn.close() else: conn.close() |
def run_heartbeat_continuously(self) -> threading.Event: """ For a long runing handler, there is a danger that we do not send a heartbeat message or activity on the connection whilst we are running the handler. With a default heartbeat of 30s, for example, there is a risk that a handler which takes more than 15s will f... |
broker will reset the connection. So we spin up another thread, where the user has marked the thread as having a long-running thread :return: an event to cancel the thread """ cancellation_event = threading.Event() # Effectively a no-op if we are not actually a long-running thread if not self._is_long_running_handler: ... |
logging.Logger) -> None: while not cancellation_event.is_set(): cnx.heartbeat_check() time.sleep(period) logger.debug("Signalled to exit long-running handler heartbeat") heartbeat_thread = threading.Thread(target=_send_heartbeat, args=(self._conn, 1, self._logger), daemon=True) self._logger.debug("Begin heartbeat threa... |
def _check(user, topic): """If the topic has it's export_control set to True then all the teams under the product team can access to the topic's resources. :param user: :param topic: :return: True if check is ok, False otherwise """ # if export_control then check the team is associated to the product, ie.: # - the curr... |
# - the product's team belongs to the user's parents teams if topic['export_control']: product = v1_utils.verify_existence_and_get(topic['product_id'], models.PRODUCTS) return (user.is_in_team(product['team_id']) or product['team_id'] in user.parent_teams_ids) return False |
def get_stream_or_content_from_request(request): """Ensure the proper content is uploaded. Stream might be already consumed by authentication process. Hence flask.request.stream might not be readable and return improper value. This methods checks if the stream has already been consumed and if so retrieve the data from ... |
request.data else: logger.info('Storing file content using request stream.') return request.stream |
def xpath_on_node(self, node, xpath, **kwargs): """ Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix na... |
isinstance(node, etree._ElementTree): # Document node lxml.etree._ElementTree has no nsmap, lookup root root = self.get_impl_root(node) namespaces_dict = root.nsmap.copy() else: namespaces_dict = node.nsmap.copy() if 'namespaces' in kwargs: namespaces_dict.update(kwargs['namespaces']) # Empty namespace prefix is not su... |
return node.xpath(xpath, namespaces=namespaces_dict) |
def _is_ns_in_ancestor(self, node, name, value): """ Return True if the given namespace name/value is defined in an ancestor of the given node, meaning that the given node need not have its own attributes to apply that namespacing. """ curr_node = self.get_node_parent(node) while curr_node.__class__ == etree._Element: ... |
'{%s}' % nodes.Node.XMLNS_URI in n: return True curr_node = self.get_node_parent(curr_node) return False |
def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_... |
(named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generi... |
correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly... |
def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith... |
does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly ... |
to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ return fallback_generic_aggregate(qs_model, ge... |
def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.object... |
specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_fi... |
def gen_etag(): """Generate random etag based on MD5.""" my_salt = gen_uuid() if six.PY2: my_salt = my_salt.decode('utf-8') elif six.PY3: my_salt = my_salt.encode('utf-8') md5 = hashlib.md5() md5.update(my_salt) return md5.hexdigest() |
def delete(self): """Delete this email report""" response = self.pingdom.request('DELETE', 'reports.shared/%s' % self.id) return response.json()['message'] |
def is_multiple_of(ref): """ Validates that x is a multiple of the reference (`x % ref == 0`) """ def is_multiple_of_ref(x): if x % ref == 0: return True else: raise IsNotMultipleOf(wrong_value=x, ref=ref) # raise Failure('x % {ref} == 0 does not hold for x={val}'.format(ref=ref, val=x)) is_multiple_of_ref.__name__ = '... |
def get_all_components(user, topic_id): """Get all components of a topic.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _C_COLUMNS) query.add_extra_condition(sql.and_( _TABLE.c.topic_id == topic_id, _TABLE.c.state != 'archived')) nb_rows = query.get_number_of_rows() ro... |
'_meta': {'count': nb_rows}}) |
def get_component_types_from_topic(topic_id, db_conn=None): """Returns the component types of a topic.""" db_conn = db_conn or flask.g.db_conn query = sql.select([models.TOPICS]).\ where(models.TOPICS.c.id == topic_id) topic = db_conn.execute(query).fetchone() topic = dict(topic) return topic['component_types'] |
def get_component_types(topic_id, remoteci_id, db_conn=None): """Returns either the topic component types or the rconfigration's component types.""" db_conn = db_conn or flask.g.db_conn rconfiguration = remotecis.get_remoteci_configuration(topic_id, remoteci_id, db_conn=db_conn) # if there is no rconfiguration associat... |
component_types, rconfiguration |
def get_last_components_by_type(component_types, topic_id, db_conn=None): """For each component type of a topic, get the last one.""" db_conn = db_conn or flask.g.db_conn schedule_components_ids = [] for ct in component_types: where_clause = sql.and_(models.COMPONENTS.c.type == ct, models.COMPONENTS.c.topic_id == topic... |
not exported.' % ct raise dci_exc.DCIException(msg, status_code=412) cmpt_id = cmpt_id[0] if cmpt_id in schedule_components_ids: msg = ('Component types %s malformed: type %s duplicated.' % (component_types, ct)) raise dci_exc.DCIException(msg, status_code=412) schedule_components_ids.append(cmpt_id) return schedule_co... |
def verify_and_get_components_ids(topic_id, components_ids, component_types, db_conn=None): """Process some verifications of the provided components ids.""" db_conn = db_conn or flask.g.db_conn if len(components_ids) != len(component_types): msg = 'The number of component ids does not match the number ' \ 'of component... |
models.COMPONENTS.c.topic_id == topic_id, models.COMPONENTS.c.export_control == True, # noqa models.COMPONENTS.c.state == 'active') query = (sql.select([models.COMPONENTS]) .where(where_clause)) cmpt = db_conn.execute(query).fetchone() if cmpt is None: msg = 'Component id %s not found or not exported' % c_id raise dci_... |
def retrieve_tags_from_component(user, c_id): """Retrieve all tags attached to a component.""" JCT = models.JOIN_COMPONENTS_TAGS query = (sql.select([models.TAGS]) .select_from(JCT.join(models.TAGS)) .where(JCT.c.component_id == c_id)) rows = flask.g.db_conn.execute(query) return flask.jsonify({'tags': rows, '_meta': {... |
def add_tag_for_component(user, c_id): """Add a tag on a specific component.""" v1_utils.verify_existence_and_get(c_id, _TABLE) values = { 'component_id': c_id } component_tagged = tags.add_tag_to_resource(values, models.JOIN_COMPONENTS_TAGS) return flask.Response(json.dumps(component_tagged), 201, content_type='applic... |
def delete_tag_for_component(user, c_id, tag_id): """Delete a tag on a specific component.""" # Todo : check c_id and tag_id exist in db query = _TABLE_TAGS.delete().where(_TABLE_TAGS.c.tag_id == tag_id and _TABLE_TAGS.c.component_id == c_id) try: flask.g.db_conn.execute(query) except sa_exc.IntegrityError: raise dci_e... |
def should_be_hidden_as_cause(exc): """ Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error """ # reduced traceback in case of HasWrongType (instance_of checks) from valid8.validation_lib.types import HasWrongType, IsWrongType return isinstance(exc, (HasWrongType, IsW... |
def is_error_of_type(exc, ref_type): """ Helper function to determine if some exception is of some type, by also looking at its declared __cause__ :param exc: :param ref_type: :return: """ if isinstance(exc, ref_type): return True elif hasattr(exc, '__cause__') and exc.__cause__ is not None: return is_error_of_type(exc... |
def _failure_raiser(validation_callable, # type: Callable failure_type=None, # type: Type[WrappingFailure] help_msg=None, # type: str **kw_context_args): # type: (...) -> Callable """ Wraps the provided validation function so that in case of failure it raises the given failure_type or a WrappingFailure with the given h... |
:param help_msg: an optional string help message for the raised `WrappingFailure` (if no failure_type is provided) :param kw_context_args: optional context arguments for the custom failure message :return: """ # check failure type if failure_type is not None and help_msg is not None: raise ValueError('Only one of failu... |
= as_function(validation_callable) # create wrapper # option (a) use the `decorate()` helper method to preserve name and signature of the inner object # ==> NO, we want to support also non-function callable objects # option (b) simply create a wrapper manually def raiser(x): """ Wraps validation_callable to raise a fai... |
as e: # no need to raise from e since the __cause__ is already set in the constructor: we can safely commonalize res = e if not result_is_success(res): typ = failure_type or WrappingFailure exc = typ(wrapped_func=validation_callable, wrong_value=x, validation_outcome=res, help_msg=help_msg, **kw_context_args) raise exc... |
message in the name since it is only used in error messages where # they will appear anyway ! # --- # if help_msg or failure_type: # raiser.__name__ = 'failure_raiser({}, {})'.format(get_callable_name(validation_callable), # help_msg or failure_type.__name__) # else: # --- # raiser.__name__ = 'failure_raiser({})'.forma... |
in any other context than # raising errors. If we want to support this, then creating a callable object with everything in the fields will be # probably more appropriate so that error messages will be able to display the inner name, while repr() will still # say that this is a failure raiser. # TODO consider transformi... |
above) return raiser |
def _none_accepter(validation_callable # type: Callable ): # type: (...) -> Callable """ Wraps the given validation callable to accept None values silently. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will return True. When any other value is recei... |
same than the validation callable for more user-friendly error messages :param validation_callable: :return: """ # option (a) use the `decorate()` helper method to preserve name and signature of the inner object # ==> NO, we want to support also non-function callable objects # option (b) simply create a wrapper manuall... |
validation_callable(x) else: # value is None: skip validation return True # set a name so that the error messages are more user-friendly accept_none.__name__ = 'skip_on_none({})'.format(get_callable_name(validation_callable)) return accept_none |
def _none_rejecter(validation_callable # type: Callable ): # type: (...) -> Callable """ Wraps the given validation callable to reject None values. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will raise a WrappingFailure. When any other value is re... |
use the `decorate()` helper method to preserve name and signature of the inner object # ==> NO, we want to support also non-function callable objects # option (b) simply create a wrapper manually def reject_none(x): if x is not None: return validation_callable(x) else: raise ValueIsNone(wrong_value=x) # set a name so t... |
see the checker reject_none.__name__ = 'reject_none({})'.format(get_callable_name(validation_callable)) return reject_none |
def get_help_msg(self, dotspace_ending=False, # type: bool **kwargs): # type: (...) -> str """ The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the instance level or at the class level. The help message is formatted according... |
dotspace_ending is set to True. :param dotspace_ending: True will append a dot and a space at the end of the message if it is not empty (default is False) :param kwargs: keyword arguments to format the help message :return: the formatted help message """ context = self.get_context_for_help_msgs(kwargs) if self.help_msg... |
it context = copy(context) # first format if needed try: help_msg = self.help_msg variables = re.findall("{\S+}", help_msg) for v in set(variables): v = v[1:-1] if v in context and len(str(context[v])) > self.__max_str_length_displayed__: new_name = '@@@@' + v + '@@@@' help_msg = help_msg.replace('{' + v + '}', '{' + n... |
# no need to raise from e, __cause__ is set in the constructor raise HelpMsgFormattingException(self.help_msg, e, context) # then add a trailing dot and space if needed if dotspace_ending: return end_with_dot_space(help_msg) else: return help_msg else: return '' |
def get_details(self): """ The function called to get the details appended to the help message when self.append_details is True """ strval = str(self.wrong_value) if len(strval) > self.__max_str_length_displayed__: return '(Actual value is too big to be printed in this message)' else: return 'Wrong value: [{}]'.format(... |
def get_details(self): """ Overrides the method in Failure so as to add a few details about the wrapped function and outcome """ if isinstance(self.validation_outcome, Exception): if isinstance(self.validation_outcome, Failure): # do not say again what was the value, it is already mentioned inside :) end_str = '' else:... |
end=end_str) else: contents = 'Function [{wrapped}] returned [{result}] for value [{value}].' \ ''.format(wrapped=get_callable_name(self.wrapped_func), result=self.validation_outcome, value=self.wrong_value) return contents |
def get_context_for_help_msgs(self, context_dict): """ We override this method from HelpMsgMixIn to replace wrapped_func with its name """ context_dict = copy(context_dict) context_dict['wrapped_func'] = get_callable_name(context_dict['wrapped_func']) return context_dict |
def validate_field(cls, field_name, *validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Callable """ A class decorator. It goes through all class variables and for all of those that are descriptors with a __set__, it wraps the descriptors' setter function with a `validate_arg` annotation :param field_... |
def validate_io(f=DECORATED, none_policy=None, # type: int _out_=None, # type: ValidationFuncs **kw_validation_funcs # type: ValidationFuncs ): """ A function decorator to add input validation prior to the function execution. It should be called with named arguments: for each function arg name, provide a single validat... |
the function, the input name, and any further information available from the validation function(s) For example: ``` def is_even(x): return x % 2 == 0 def gt(a): def gt(x): return x >= a return gt @validate_io(a=[is_even, gt(1)], b=is_even) def myfunc(a, b): print('hello') ``` will generate the equivalent of : ``` def ... |
raise InputValidationError(...) ``` :param none_policy: describes how None values should be handled. See `NoneArgPolicy` for the various possibilities. Default is `NoneArgPolicy.ACCEPT_IF_OPTIONAl_ELSE_VALIDATE`. :param _out_: a validation function or list of validation functions to apply to the function output. See kw... |
use. A validation function may be a callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/py... |
before executing the function's code everytime it is executed. """ return decorate_several_with_validation(f, none_policy=none_policy, _out_=_out_, **kw_validation_funcs) |
def validate_arg(f, arg_name, *validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ A decorator to apply function input validation for the given argument name, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked... |
the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [... |
subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param none_policy: describes how None values should be handled. See `NoneArg... |
in the exception, and that may be also used to format the help message :return: a function decorator, able to transform a function into a function that will perform input validation before executing the function's code everytime it is executed. """ return decorate_with_validation(f, arg_name, *validation_func, **kwargs... |
def validate_out(*validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Callable """ A decorator to apply function output validation to this function's output, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.