code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
@wraps(func) def func_wrapper(*args, **kwargs): # pylint: disable=C0111, C0103 function_name = func.__name__ CHECKERS_DISABLED = os.getenv('CHECKERS_DISABLED', '') disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split(',')] force_run = kwargs.get('force_run', False) if function_name in disabled_functions and not force_run: return True else: return func(*args, **kwargs) return func_wrapper
def disable_checker_on_env(func)
Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, ``True``. If enabled, the result of ``func``.
2.543093
2.50989
1.013229
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if isinstance(value, uuid_.UUID): return value try: value = uuid_.UUID(value) except ValueError: raise errors.CannotCoerceError('value (%s) cannot be coerced to a valid UUID') return value
def uuid(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` coerced to a :class:`UUID <python:uuid.UUID>` object / :obj:`None <python:None>` :rtype: :class:`UUID <python:uuid.UUID>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` cannot be coerced to a :class:`UUID <python:uuid.UUID>`
3.231413
3.061227
1.055594
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None minimum_length = integer(minimum_length, allow_empty = True) maximum_length = integer(maximum_length, allow_empty = True) if coerce_value: value = str(value) elif not isinstance(value, basestring): raise errors.CannotCoerceError('value (%s) was not coerced to a string' % value) if value and maximum_length and len(value) > maximum_length: raise errors.MaximumLengthError( 'value (%s) exceeds maximum length %s' % (value, maximum_length) ) if value and minimum_length and len(value) < minimum_length: if whitespace_padding: value = value.ljust(minimum_length, ' ') else: raise errors.MinimumLengthError( 'value (%s) is below the minimum length %s' % (value, minimum_length) ) return value
def string(value, allow_empty = False, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs)
Validate that ``value`` is a valid string. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if it is not already. If ``False``, will raise a :class:`ValueError` if ``value`` is not a string. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value`` is ``False`` :raises MinimumLengthError: if ``minimum_length`` is supplied and the length of ``value`` is less than ``minimum_length`` and ``whitespace_padding`` is ``False`` :raises MaximumLengthError: if ``maximum_length`` is supplied and the length of ``value`` is more than the ``maximum_length``
1.893182
1.876246
1.009026
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif value is None: return None minimum_length = integer(minimum_length, allow_empty = True, force_run = True) # pylint: disable=E1123 maximum_length = integer(maximum_length, allow_empty = True, force_run = True) # pylint: disable=E1123 if isinstance(value, forbid_literals) or not hasattr(value, '__iter__'): raise errors.NotAnIterableError('value type (%s) not iterable' % type(value)) if value and minimum_length is not None and len(value) < minimum_length: raise errors.MinimumLengthError( 'value has fewer items than the minimum length %s' % minimum_length ) if value and maximum_length is not None and len(value) > maximum_length: raise errors.MaximumLengthError( 'value has more items than the maximum length %s' % maximum_length ) return value
def iterable(value, allow_empty = False, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs)
Validate that ``value`` is a valid iterable. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param forbid_literals: A collection of literals that will be considered invalid even if they are (actually) iterable. Defaults to :class:`str <python:str>` and :class:`bytes <python:bytes>`. :type forbid_literals: iterable :param minimum_length: If supplied, indicates the minimum number of members needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of members needed to be valid. :type maximum_length: :class:`int <python:int>` :returns: ``value`` / :obj:`None <python:None>` :rtype: iterable / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises NotAnIterableError: if ``value`` is not a valid iterable or :obj:`None <python:None>` :raises MinimumLengthError: if ``minimum_length`` is supplied and the length of ``value`` is less than ``minimum_length`` and ``whitespace_padding`` is ``False`` :raises MaximumLengthError: if ``maximum_length`` is supplied and the length of ``value`` is more than the ``maximum_length``
2.223742
2.201922
1.00991
if value is not None and not value and allow_empty: pass elif (value is not None and not value) or value: raise errors.NotNoneError('value was not None') return None
def none(value, allow_empty = False, **kwargs)
Validate that ``value`` is :obj:`None <python:None>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty but **not** :obj:`None <python:None>`. If ``False``, raises a :class:`NotNoneError` if ``value`` is empty but **not** :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: :obj:`None <python:None>` :raises NotNoneError: if ``allow_empty`` is ``False`` and ``value`` is empty but **not** :obj:`None <python:None>` and
5.965686
10.292777
0.579599
if not value and allow_empty: return None elif not value: raise errors.EmptyValueError('value was empty') return value
def not_empty(value, allow_empty = False, **kwargs)
Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
5.529801
12.308856
0.449254
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None try: parse('%s = None' % value) except (SyntaxError, ValueError, TypeError): raise errors.InvalidVariableNameError( 'value (%s) is not a valid variable name' % value ) return value
def variable_name(value, allow_empty = False, **kwargs)
Validate that the value is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or class, or function, etc.) name. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` or :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
3.940062
4.02952
0.977799
original_value = value if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if json_serializer is None: json_serializer = json_ if isinstance(value, str): try: value = json_serializer.loads(value) except Exception: raise errors.CannotCoerceError( 'value (%s) cannot be coerced to a dict' % original_value ) value = dict(value, json_serializer = json_serializer) if not isinstance(value, dict_): raise errors.NotADictError('value (%s) is not a dict' % original_value) return value
def dict(value, allow_empty = False, json_serializer = None, **kwargs)
Validate that ``value`` is a :class:`dict <python:dict>`. .. hint:: If ``value`` is a string, this validator will assume it is a JSON object and try to convert it into a :class:`dict <python:dict>` You can override the JSON serializer used by passing it to the ``json_serializer`` property. By default, will utilize the Python :class:`json <json>` encoder/decoder. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param json_serializer: The JSON encoder/decoder to use to deserialize a string passed in ``value``. If not supplied, will default to the Python :class:`json <python:json>` encoder/decoder. :type json_serializer: callable :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`dict <python:dict>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` cannot be coerced to a :class:`dict <python:dict>` :raises NotADictError: if ``value`` is not a :class:`dict <python:dict>`
2.942815
2.534301
1.161194
original_value = value original_schema = schema if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not json_serializer: json_serializer = json_ if isinstance(value, str): try: value = json_serializer.loads(value) except Exception: raise errors.CannotCoerceError( 'value (%s) cannot be deserialized from JSON' % original_value ) if isinstance(schema, str): try: schema = dict(schema, allow_empty = allow_empty, json_serializer = json_serializer, **kwargs) except Exception: raise errors.CannotCoerceError( 'schema (%s) cannot be coerced to a dict' % original_schema ) if not isinstance(value, (list, dict_)): raise errors.NotJSONError('value (%s) is not a JSON object' % original_value) if original_schema and not isinstance(schema, dict_): raise errors.NotJSONError('schema (%s) is not a JSON object' % original_schema) if not schema: return value try: jsonschema.validate(value, schema) except jsonschema.exceptions.ValidationError as error: raise errors.JSONValidationError(error.message) except jsonschema.exceptions.SchemaError as error: raise errors.NotJSONSchemaError(error.message) return value
def json(value, schema = None, allow_empty = False, json_serializer = None, **kwargs)
Validate that ``value`` conforms to the supplied JSON Schema. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. .. hint:: If either ``value`` or ``schema`` is a string, this validator will assume it is a JSON object and try to convert it into a :class:`dict <python:dict>`. You can override the JSON serializer used by passing it to the ``json_serializer`` property. By default, will utilize the Python :class:`json <json>` encoder/decoder. :param value: The value to validate. :param schema: An optional JSON Schema against which ``value`` will be validated. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param json_serializer: The JSON encoder/decoder to use to deserialize a string passed in ``value``. If not supplied, will default to the Python :class:`json <python:json>` encoder/decoder. :type json_serializer: callable :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of :class:`dict <python:dict>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` cannot be coerced to a :class:`dict <python:dict>` :raises NotJSONError: if ``value`` cannot be deserialized from JSON :raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object :raises JSONValidationError: if ``value`` does not validate against the JSON Schema
2.263262
2.096508
1.079539
if maximum is None: maximum = POSITIVE_INFINITY else: maximum = numeric(maximum) if minimum is None: minimum = NEGATIVE_INFINITY else: minimum = numeric(minimum) if value is None and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif value is not None: if isinstance(value, str): try: value = float_(value) except (ValueError, TypeError): raise errors.CannotCoerceError( 'value (%s) cannot be coerced to a numeric form' % value ) elif not isinstance(value, numeric_types): raise errors.CannotCoerceError( 'value (%s) is not a numeric type, was %s' % (value, type(value)) ) if value is not None and value > maximum: raise errors.MaximumValueError( 'value (%s) exceeds maximum (%s)' % (value, maximum) ) if value is not None and value < minimum: raise errors.MinimumValueError( 'value (%s) less than minimum (%s)' % (value, minimum) ) return value
def numeric(value, allow_empty = False, minimum = None, maximum = None, **kwargs)
Validate that ``value`` is a numeric value. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises an :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and ``allow_empty`` is ``False`` :raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the ``minimum`` :raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the ``maximum`` :raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form
2.102543
2.088633
1.00666
value = numeric(value, # pylint: disable=E1123 allow_empty = allow_empty, minimum = minimum, maximum = maximum, force_run = True) if value is not None and hasattr(value, 'is_integer'): if value.is_integer(): return int(value) if value is not None and coerce_value: float_value = math.ceil(value) if is_py2: value = int(float_value) # pylint: disable=R0204 elif is_py3: str_value = str(float_value) value = int(str_value, base = base) else: raise NotImplementedError('Python %s not supported' % os.sys.version) elif value is not None and not isinstance(value, integer_types): raise errors.NotAnIntegerError('value (%s) is not an integer-type, ' 'is a %s'% (value, type(value)) ) return value
def integer(value, allow_empty = False, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs)
Validate that ``value`` is an :class:`int <python:int>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param coerce_value: If ``True``, will force any numeric ``value`` to an integer (always rounding up). If ``False``, will raise an error if ``value`` is numeric but not a whole number. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :param base: Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to ``10``. :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and ``allow_empty`` is ``False`` :raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the ``minimum`` :raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the ``maximum`` :raises NotAnIntegerError: if ``coerce_value`` is ``False``, and ``value`` is not an integer :raises CannotCoerceError: if ``value`` cannot be coerced to an :class:`int <python:int>`
3.609133
3.879028
0.930422
try: value = _numeric_coercion(value, coercion_function = float_, allow_empty = allow_empty, minimum = minimum, maximum = maximum) except (errors.EmptyValueError, errors.CannotCoerceError, errors.MinimumValueError, errors.MaximumValueError) as error: raise error except Exception as error: raise errors.CannotCoerceError('unable to coerce value (%s) to float, ' 'for an unknown reason - please see ' 'stack trace' % value) return value
def float(value, allow_empty = False, minimum = None, maximum = None, **kwargs)
Validate that ``value`` is a :class:`float <python:float>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`float <python:float>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and ``allow_empty`` is ``False`` :raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the ``minimum`` :raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the ``maximum`` :raises CannotCoerceError: if unable to coerce ``value`` to a :class:`float <python:float>`
3.720798
3.469274
1.072501
try: value = _numeric_coercion(value, coercion_function = fractions.Fraction, allow_empty = allow_empty, minimum = minimum, maximum = maximum) except (errors.EmptyValueError, errors.CannotCoerceError, errors.MinimumValueError, errors.MaximumValueError) as error: raise error except Exception as error: raise errors.CannotCoerceError('unable to coerce value (%s) to Fraction, ' 'for an unknown reason - please see ' 'stack trace' % value) return value
def fraction(value, allow_empty = False, minimum = None, maximum = None, **kwargs)
Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`Fraction <python:fractions.Fraction>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and ``allow_empty`` is ``False`` :raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the ``minimum`` :raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the ``maximum`` :raises CannotCoerceError: if unable to coerce ``value`` to a :class:`Fraction <python:fractions.Fraction>`
3.754601
3.38838
1.108081
if value is None and allow_empty: return None elif value is None: raise errors.EmptyValueError('value cannot be None') if isinstance(value, str): try: value = decimal_.Decimal(value.strip()) except decimal_.InvalidOperation: raise errors.CannotCoerceError( 'value (%s) cannot be converted to a Decimal' % value ) elif isinstance(value, fractions.Fraction): try: value = float(value, force_run = True) # pylint: disable=R0204, E1123 except ValueError: raise errors.CannotCoerceError( 'value (%s) cannot be converted to a Decimal' % value ) value = numeric(value, # pylint: disable=E1123 allow_empty = False, maximum = maximum, minimum = minimum, force_run = True) if not isinstance(value, decimal_.Decimal): value = decimal_.Decimal(value) return value
def decimal(value, allow_empty = False, minimum = None, maximum = None, **kwargs)
Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`Decimal <python:decimal.Decimal>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and ``allow_empty`` is ``False`` :raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the ``minimum`` :raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the ``maximum`` :raises CannotCoerceError: if unable to coerce ``value`` to a :class:`Decimal <python:decimal.Decimal>`
3.013027
3.164121
0.952248
if coercion_function is None: raise errors.CoercionFunctionEmptyError('coercion_function cannot be empty') elif not hasattr(coercion_function, '__call__'): raise errors.NotCallableError('coercion_function must be callable') value = numeric(value, # pylint: disable=E1123 allow_empty = allow_empty, minimum = minimum, maximum = maximum, force_run = True) if value is not None: try: value = coercion_function(value) except (ValueError, TypeError, AttributeError, IndexError, SyntaxError): raise errors.CannotCoerceError( 'cannot coerce value (%s) to desired type' % value ) return value
def _numeric_coercion(value, coercion_function = None, allow_empty = False, minimum = None, maximum = None)
Validate that ``value`` is numeric and coerce using ``coercion_function``. :param value: The value to validate. :param coercion_function: The function to use to coerce ``value`` to the desired type. :type coercion_function: callable :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: the type returned by ``coercion_function`` :raises CoercionFunctionEmptyError: if ``coercion_function`` is empty :raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``coercion_function`` raises an :class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`, :class:`AttributeError <python:AttributeError>`, :class:`IndexError <python:IndexError>, or :class:`SyntaxError <python:SyntaxError>`
2.888283
2.866806
1.007492
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, io.BytesIO): raise errors.NotBytesIOError('value (%s) is not a BytesIO, ' 'is a %s' % (value, type(value))) return value
def bytesIO(value, allow_empty = False, **kwargs)
Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`BytesIO <python:io.BytesIO>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises NotBytesIOError: if ``value`` is not a :class:`BytesIO <python:io.BytesIO>` object.
3.151238
2.999169
1.050704
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, io.StringIO): raise ValueError('value (%s) is not an io.StringIO object, ' 'is a %s' % (value, type(value))) return value
def stringIO(value, allow_empty = False, **kwargs)
Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`StringIO <python:io.StringIO>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises NotStringIOError: if ``value`` is not a :class:`StringIO <python:io.StringIO>` object
3.2952
3.685944
0.893991
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if hasattr(os, 'PathLike'): if not isinstance(value, (str, bytes, int, os.PathLike)): # pylint: disable=E1101 raise errors.NotPathlikeError('value (%s) is path-like' % value) else: if not isinstance(value, int): try: os.path.exists(value) except TypeError: raise errors.NotPathlikeError('value (%s) is not path-like' % value) return value
def path(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid path-like object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: The path represented by ``value``. :rtype: Path-like object / :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotPathlikeError: if ``value`` is not a valid path-like object
2.949256
2.963717
0.995121
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None value = path(value, force_run = True) # pylint: disable=E1123 if not os.path.exists(value): raise errors.PathExistsError('value (%s) not found' % value) return value
def path_exists(value, allow_empty = False, **kwargs)
Validate that ``value`` is a path-like object that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: The file name represented by ``value``. :rtype: Path-like object / :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotPathlikeError: if ``value`` is not a path-like object :raises PathExistsError: if ``value`` does not exist
4.387241
4.872941
0.900327
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None value = path_exists(value, force_run = True) # pylint: disable=E1123 if not os.path.isfile(value): raise errors.NotAFileError('value (%s) is not a file') return value
def file_exists(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid file that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: The file name represented by ``value``. :rtype: Path-like object / :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotPathlikeError: if ``value`` is not a path-like object :raises PathExistsError: if ``value`` does not exist on the local filesystem :raises NotAFileError: if ``value`` is not a valid file
4.368712
4.721759
0.92523
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None value = path_exists(value, force_run = True) # pylint: disable=E1123 if not os.path.isdir(value): raise errors.NotADirectoryError('value (%s) is not a directory' % value) return value
def directory_exists(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid directory that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: The file name represented by ``value``. :rtype: Path-like object / :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotPathlikeError: if ``value`` is not a path-like object :raises PathExistsError: if ``value`` does not exist on the local filesystem :raises NotADirectoryError: if ``value`` is not a valid directory
3.838994
4.439734
0.86469
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None value = file_exists(value, force_run = True) # pylint: disable=E1123 try: with open(value, mode='r'): pass except (OSError, IOError): raise errors.NotReadableError('file at %s could not be opened for ' 'reading' % value) return value
def readable(value, allow_empty = False, **kwargs)
Validate that ``value`` is a path to a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when reading from a file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'r') as file_object: # read from file here except (OSError, IOError) as error: # Handle an error if unable to write. :param value: The path to a file on the local filesystem whose readability is to be validated. :type value: Path-like object :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: Validated path-like object or :obj:`None <python:None>` :rtype: Path-like object or :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotPathlikeError: if ``value`` is not a path-like object :raises PathExistsError: if ``value`` does not exist on the local filesystem :raises NotAFileError: if ``value`` is not a valid file :raises NotReadableError: if ``value`` cannot be opened for reading
4.494546
4.586723
0.979904
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None value = path(value, force_run = True) if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') is_valid = os.access(value, mode = os.W_OK) if not is_valid: raise errors.NotWriteableError('writing not allowed for file at %s' % value) return value
def writeable(value, allow_empty = False, **kwargs)
Validate that ``value`` is a path to a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to write to it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'a') as file_object: # write to file here except (OSError, IOError) as error: # Handle an error if unable to write. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The path to a file on the local filesystem whose writeability is to be validated. :type value: Path-like object :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: Validated absolute path or :obj:`None <python:None>` :rtype: Path-like object or :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotImplementedError: if used on a Windows system :raises NotPathlikeError: if ``value`` is not a path-like object :raises NotWriteableError: if ``value`` cannot be opened for writing
4.26117
4.440789
0.959553
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None value = file_exists(value, force_run = True) if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') is_valid = os.access(value, mode = os.X_OK) if not is_valid: raise errors.NotExecutableError('execution not allowed for file at %s' % value) return value
def executable(value, allow_empty = False, **kwargs)
Validate that ``value`` is a path to an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the executability of a file *before* attempting to execute it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to execute the file using a ``try ... except`` block. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is executable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The path to a file on the local filesystem whose writeability is to be validated. :type value: Path-like object :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: Validated absolute path or :obj:`None <python:None>` :rtype: Path-like object or :obj:`None <python:None>` :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty :raises NotImplementedError: if used on a Windows system :raises NotPathlikeError: if ``value`` is not a path-like object :raises NotAFileError: if ``value`` does not exist on the local file system :raises NotExecutableError: if ``value`` cannot be executed
4.154225
4.367968
0.951066
is_recursive = kwargs.pop('is_recursive', False) if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, basestring): raise errors.CannotCoerceError('value must be a valid string, ' 'was %s' % type(value)) value = value.lower() is_valid = False stripped_value = None for protocol in URL_PROTOCOLS: if protocol in value: stripped_value = value.replace(protocol, '') for special_use_domain in SPECIAL_USE_DOMAIN_NAMES: if special_use_domain in value: if stripped_value: try: domain(stripped_value, allow_empty = False, is_recursive = is_recursive) is_valid = True except (ValueError, TypeError): pass if not is_valid and allow_special_ips: try: ip_address(stripped_value, allow_empty = False) is_valid = True except (ValueError, TypeError): pass if not is_valid: is_valid = URL_REGEX.match(value) if not is_valid and allow_special_ips: is_valid = URL_SPECIAL_IP_REGEX.match(value) if not is_valid: raise errors.InvalidURLError('value (%s) is not a valid URL' % value) return value
def url(value, allow_empty = False, allow_special_ips = False, **kwargs)
Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, `RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of string parsing and regular expressions, This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :param allow_special_ips: If ``True``, will succeed when validating special IP addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``, will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults to ``False``. :type allow_special_ips: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or :obj:`None <python:None>` :raises InvalidURLError: if ``value`` is not a valid URL or empty with ``allow_empty`` set to ``True``
2.520511
2.455645
1.026415
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if is_py2 and value and isinstance(value, unicode): value = value.encode('utf-8') try: value = ipv6(value, force_run = True) # pylint: disable=E1123 ipv6_failed = False except ValueError: ipv6_failed = True if ipv6_failed: try: value = ipv4(value, force_run = True) # pylint: disable=E1123 except ValueError: raise errors.InvalidIPAddressError('value (%s) is not a valid IPv6 or ' 'IPv4 address' % value) return value
def ip_address(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid IP address. .. note:: First, the validator will check if the address is a valid IPv6 address. If that doesn't work, the validator will check if the address is a valid IPv4 address. If neither works, the validator will raise an error (as always). :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with ``allow_empty`` set to ``True``
2.968868
2.899036
1.024088
if not value and allow_empty is False: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None try: components = value.split('.') except AttributeError: raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value) if len(components) != 4 or not all(x.isdigit() for x in components): raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value) for x in components: try: x = integer(x, minimum = 0, maximum = 255) except ValueError: raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value) return value
def ipv4(value, allow_empty = False)
Validate that ``value`` is a valid IP version 4 address. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or empty with ``allow_empty`` set to ``True``
2.274076
2.243396
1.013675
if not value and allow_empty is False: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, str): raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value) value = value.lower().strip() is_valid = IPV6_REGEX.match(value) if not is_valid: raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value) return value
def ipv6(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or empty with ``allow_empty`` is not set to ``True``
2.623846
2.503707
1.047984
if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, basestring): raise errors.CannotCoerceError('value must be a valid string, ' 'was %s' % type(value)) if '-' in value: value = value.replace('-', ':') value = value.lower().strip() is_valid = MAC_ADDRESS_REGEX.match(value) if not is_valid: raise errors.InvalidMACAddressError('value (%s) is not a valid MAC ' 'address' % value) return value
def mac_address(value, allow_empty = False, **kwargs)
Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>` or string-like object :raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with ``allow_empty`` set to ``True``
2.73198
2.54044
1.075396
if not is_iterable(type_): type_ = [type_] return_value = False for check_for_type in type_: if isinstance(check_for_type, type): return_value = isinstance(obj, check_for_type) elif obj.__class__.__name__ == check_for_type: return_value = True else: return_value = _check_base_classes(obj.__class__.__bases__, check_for_type) if return_value is True: break return return_value
def is_type(obj, type_, **kwargs)
Indicate if ``obj`` is a type in ``type_``. .. hint:: This checker is particularly useful when you want to evaluate whether ``obj`` is of a particular type, but importing that type directly to use in :func:`isinstance() <python:isinstance>` would cause a circular import error. To use this checker in that kind of situation, you can instead pass the *name* of the type you want to check as a string in ``type_``. The checker will evaluate it and see whether ``obj`` is of a type or inherits from a type whose name matches the string you passed. :param obj: The object whose type should be checked. :type obj: :class:`object <python:object>` :param type_: The type(s) to check against. :type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` / :class:`str <python:str>` with type name / iterable of :class:`str <python:str>` with type name :returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.442179
2.93203
0.832931
return_value = False for base in base_classes: if base.__name__ == check_for_type: return_value = True break else: return_value = _check_base_classes(base.__bases__, check_for_type) if return_value is True: break return return_value
def _check_base_classes(base_classes, check_for_type)
Indicate whether ``check_for_type`` exists in ``base_classes``.
1.95382
1.807426
1.080996
if len(args) == 1: return True first_item = args[0] for item in args[1:]: if type(item) != type(first_item): # pylint: disable=C0123 return False if isinstance(item, dict): if not are_dicts_equivalent(item, first_item): return False elif hasattr(item, '__iter__') and not isinstance(item, (str, bytes, dict)): if len(item) != len(first_item): return False for value in item: if value not in first_item: return False for value in first_item: if value not in item: return False else: if item != first_item: return False return True
def are_equivalent(*args, **kwargs)
Indicate if arguments passed to this function are equivalent. .. hint:: This checker operates recursively on the members contained within iterables and :class:`dict <python:dict>` objects. .. caution:: If you only pass one argument to this checker - even if it is an iterable - the checker will *always* return ``True``. To evaluate members of an iterable for equivalence, you should instead unpack the iterable into the function like so: .. code-block:: python obj = [1, 1, 1, 2] result = are_equivalent(*obj) # Will return ``False`` by unpacking and evaluating the iterable's members result = are_equivalent(obj) # Will always return True :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` are equivalent, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
1.957888
2.25554
0.868035
# pylint: disable=too-many-return-statements if not args: return False if len(args) == 1: return True if not all(is_dict(x) for x in args): return False first_item = args[0] for item in args[1:]: if len(item) != len(first_item): return False for key in item: if key not in first_item: return False if not are_equivalent(item[key], first_item[key]): return False for key in first_item: if key not in item: return False if not are_equivalent(first_item[key], item[key]): return False return True
def are_dicts_equivalent(*args, **kwargs)
Indicate if :ref:`dicts <python:dict>` passed to this function have identical keys and values. :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
1.706794
1.936123
0.881552
if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') if value is None: return False if minimum is not None and maximum is None: return value >= minimum elif minimum is None and maximum is not None: return value <= maximum elif minimum is not None and maximum is not None: return value >= minimum and value <= maximum
def is_between(value, minimum = None, maximum = None, **kwargs)
Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support comparison operators, whether they are numbers or not. Technically, this means that ``value``, ``minimum``, or ``maximum`` need to implement the Python magic methods :func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`. If ``value``, ``minimum``, or ``maximum`` do not support comparison operators, they will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports comparison operators :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: anything that supports comparison operators / :obj:`None <python:None>` :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: anything that supports comparison operators / :obj:`None <python:None>` :returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not support comparison operators :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>`
1.793491
2.153204
0.832941
if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') length = len(value) minimum = validators.numeric(minimum, allow_empty = True) maximum = validators.numeric(maximum, allow_empty = True) return is_between(length, minimum = minimum, maximum = maximum)
def has_length(value, minimum = None, maximum = None, **kwargs)
Indicate whether ``value`` has a length greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that supports the :func:`len() <python:len>` operation. This means that ``value`` must implement the :func:`__len__ <python:__len__>` magic method. If ``value`` does not support length evaluation, the checker will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports length evaluation :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` has length greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises TypeError: if ``value`` does not support length evaluation :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>`
2.932906
3.605011
0.813564
if isinstance(value, dict): return True try: value = validators.dict(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_dict(value, **kwargs)
Indicate whether ``value`` is a valid :class:`dict <python:dict>` .. note:: This will return ``True`` even if ``value`` is an empty :class:`dict <python:dict>`. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
4.326828
4.834694
0.894954
try: value = validators.json(value, schema = schema, json_serializer = json_serializer, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_json(value, schema = None, json_serializer = None, **kwargs)
Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. :param value: The value to evaluate. :param schema: An optional JSON schema against which ``value`` will be validated. :type schema: :class:`dict <python:dict>` / :class:`str <python:str>` / :obj:`None <python:None>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
3.409239
4.218251
0.808211
if value is None: return False minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs) maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs) if isinstance(value, basestring) and not value: if minimum_length and minimum_length > 0 and not whitespace_padding: return False return True try: value = validators.string(value, coerce_value = coerce_value, minimum_length = minimum_length, maximum_length = maximum_length, whitespace_padding = whitespace_padding, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs)
Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.185538
2.402227
0.909797
if obj is None: return False if obj in forbid_literals: return False try: obj = validators.iterable(obj, allow_empty = True, forbid_literals = forbid_literals, minimum_length = minimum_length, maximum_length = maximum_length, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_iterable(obj, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs)
Indicate whether ``obj`` is iterable. :param forbid_literals: A collection of literals that will be considered invalid even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>` containing :class:`str <python:str>` and :class:`bytes <python:bytes>`. :type forbid_literals: iterable :param minimum_length: If supplied, indicates the minimum number of members needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of members needed to be valid. :type maximum_length: :class:`int <python:int>` :returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.755641
2.981413
0.924274
try: value = validators.not_empty(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_not_empty(value, **kwargs)
Indicate whether ``value`` is empty. :param value: The value to evaluate. :returns: ``True`` if ``value`` is empty, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.272691
5.589655
0.943295
try: validators.none(value, allow_empty = allow_empty, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_none(value, allow_empty = False, **kwargs)
Indicate whether ``value`` is :obj:`None <python:None>`. :param value: The value to evaluate. :param allow_empty: If ``True``, accepts falsey values as equivalent to :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is :obj:`None <python:None>`, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
4.402819
5.076979
0.867212
try: validators.variable_name(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_variable_name(value, **kwargs)
Indicate whether ``value`` is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or class, or function, etc.) name. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.115937
6.296345
0.812525
try: validators.uuid(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_uuid(value, **kwargs)
Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>` :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
6.003242
5.985599
1.002948
try: value = validators.date(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_date(value, minimum = None, maximum = None, coerce_value = False, **kwargs)
Indicate whether ``value`` is a :class:`date <python:datetime.date>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`date <python:datetime.date>`. If ``False``, will only return ``True`` if ``value`` is a date value only. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.814499
3.282042
0.857545
try: value = validators.datetime(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_datetime(value, minimum = None, maximum = None, coerce_value = False, **kwargs)
Indicate whether ``value`` is a :class:`datetime <python:datetime.datetime>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`datetime <python:datetime.datetime>`. If ``False``, will only return ``True`` if ``value`` is a complete timestamp. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.893911
3.307736
0.874892
try: value = validators.time(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_time(value, minimum = None, maximum = None, coerce_value = False, **kwargs)
Indicate whether ``value`` is a :class:`time <python:datetime.time>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`time <python:datetime.time>`. If ``False``, will only return ``True`` if ``value`` is a valid time. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.847406
3.484807
0.817091
try: value = validators.timezone(value, positive = positive, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_timezone(value, positive = True, **kwargs)
Indicate whether ``value`` is a :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** validate whether the value is a timezone that actually exists, nor can it resolve timzone names (e.g. ``'Eastern'`` or ``'CET'``). For that kind of functionality, we recommend you utilize: `pytz <https://pypi.python.org/pypi/pytz>`_ :param value: The value to evaluate. :param positive: Indicates whether the ``value`` is positive or negative (only has meaning if ``value`` is a string). Defaults to ``True``. :type positive: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
4.267237
5.748731
0.742292
try: value = validators.numeric(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_numeric(value, minimum = None, maximum = None, **kwargs)
Indicate whether ``value`` is a numeric value. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
3.652071
4.400803
0.829865
try: value = validators.integer(value, coerce_value = coerce_value, minimum = minimum, maximum = maximum, base = base, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_integer(value, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs)
Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :param base: Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to ``10``. :type base: :class:`int <python:int>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
2.703679
3.066103
0.881797
try: value = validators.float(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_float(value, minimum = None, maximum = None, **kwargs)
Indicate whether ``value`` is a :class:`float <python:float>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
3.682455
4.191117
0.878633
try: value = validators.fraction(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_fraction(value, minimum = None, maximum = None, **kwargs)
Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
3.771114
4.462838
0.845004
try: value = validators.decimal(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_decimal(value, minimum = None, maximum = None, **kwargs)
Indicate whether ``value`` contains a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
3.66173
4.466025
0.819908
try: value = validators.path(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_pathlike(value, **kwargs)
Indicate whether ``value`` is a path-like object. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
6.365739
5.910589
1.077006
try: value = validators.path_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_on_filesystem(value, **kwargs)
Indicate whether ``value`` is a file or directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
6.529611
6.373923
1.024426
try: value = validators.file_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_file(value, **kwargs)
Indicate whether ``value`` is a file that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
6.174714
5.962382
1.035612
try: value = validators.directory_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_directory(value, **kwargs)
Indicate whether ``value`` is a directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
6.096351
6.160392
0.989604
try: validators.readable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_readable(value, **kwargs)
Indicate whether ``value`` is a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when reading from a file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'r') as file_object: # read from file here except (OSError, IOError) as error: # Handle an error if unable to write. :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
6.515746
6.44963
1.010251
if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') try: validators.writeable(value, allow_empty = False, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_writeable(value, **kwargs)
Indicate whether ``value`` is a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to write to it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'a') as file_object: # write to file here except (OSError, IOError) as error: # Handle an error if unable to write. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
4.812565
5.414029
0.888906
if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') try: validators.executable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_executable(value, **kwargs)
Indicate whether ``value`` is an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to execute it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to execute the file using a ``try ... except`` block. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.002943
6.018492
0.831262
try: value = validators.email(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_email(value, **kwargs)
Indicate whether ``value`` is an email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions. String parsing in particular is used to validate certain *highly unusual* but still valid email patterns, including the use of escaped text and comments within an email address' local address (the user name part). This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.328329
6.115668
0.871259
try: value = validators.url(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_url(value, **kwargs)
Indicate whether ``value`` is a URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, `RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of string parsing and regular expressions, This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :param allow_special_ips: If ``True``, will succeed when validating special IP addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``, will fail if ``value`` is a special IP address. Defaults to ``False``. :type allow_special_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.231785
5.847943
0.894637
try: value = validators.domain(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_domain(value, **kwargs)
Indicate whether ``value`` is a valid domain. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value`` resembles a valid domain name. It is - generally - compliant with `RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges in a number of key ways: * Including authentication (e.g. ``username:[email protected]``) will fail validation. * Including a path (e.g. ``domain.dev/path/to/file``) will fail validation. * Including a port (e.g. ``domain.dev:8080``) will fail validation. If you are hoping to validate a more complete URL, we recommend that you see :func:`url <validator_collection.validators.url>`. :param value: The value to evaluate. :param allow_ips: If ``True``, will succeed when validating IP addresses, If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``. :type allow_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.282277
5.745692
0.919346
try: value = validators.ip_address(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_ip_address(value, **kwargs)
Indicate whether ``value`` is a valid IP address (version 4 or version 6). :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.144693
5.110519
1.006687
try: value = validators.ipv4(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_ipv4(value, **kwargs)
Indicate whether ``value`` is a valid IP version 4 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.139691
5.367469
0.957563
try: value = validators.ipv6(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_ipv6(value, **kwargs)
Indicate whether ``value`` is a valid IP version 6 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
5.221391
5.366229
0.973009
try: value = validators.mac_address(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def is_mac_address(value, **kwargs)
Indicate whether ``value`` is a valid MAC address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
4.968051
5.226463
0.950557
'''Draw a series of elements from left to right''' tag = self.get_tag() c = self.canvas s = self.style sep = s.h_sep exx = 0 exy = 0 terms = lx if ltor else reversed(lx) # Reverse so we can draw left to right for term in terms: t, texx, texy = self.draw_diagram(term, ltor) # Draw each element if exx > 0: # Second element onward xn = exx + sep # Add space between elements c.move(t, xn, exy) # Shift last element forward arr = 'last' if ltor else 'first' c.create_line(exx-1, exy, xn, exy, tags=(tag,), width=s.line_width, arrow=arr) # Connecting line (NOTE: -1 fudge) exx = xn + texx # Start at end of this element else: # First element exx = texx # Start at end of this element exy = texy c.addtag_withtag(tag, t) # Retag this element c.dtag(t, t) # Drop old tags if exx == 0: # Nothing drawn, Add a line segment with an arrow in the middle exx = sep * 2 c.create_line(0,0,sep,0, width=s.line_width, tags=(tag,), arrow='last') c.create_line(sep, 0,exx,0, width=s.line_width, tags=(tag,)) exx = sep return [tag, exx, exy]
def draw_line(self, lx, ltor)
Draw a series of elements from left to right
5.232769
5.113066
1.023411
# get models all_models = apps.get_models() # get fields fields = [] for model in all_models: for field in model._meta.get_fields(): if isinstance(field, models.FileField): fields.append(field) return fields
def get_file_fields()
Get all fields which are inherited from FileField
2.809601
2.510171
1.119287
for filename in files: os.remove(os.path.join(settings.MEDIA_ROOT, filename))
def remove_media(files)
Delete file from media dir
2.716721
2.595009
1.046902
if not path: path = settings.MEDIA_ROOT if not os.path.isdir(path): return False listdir = [os.path.join(path, filename) for filename in os.listdir(path)] if all(list(map(remove_empty_dirs, listdir))): os.rmdir(path) return True else: return False
def remove_empty_dirs(path=None)
Recursively delete empty directories; return True if everything was deleted.
2.454915
2.246879
1.092589
media = set() for field in get_file_fields(): is_null = { '%s__isnull' % field.name: True, } is_empty = { '%s' % field.name: '', } storage = field.storage for value in field.model.objects \ .values_list(field.name, flat=True) \ .exclude(**is_empty).exclude(**is_null): if value not in EMPTY_VALUES: media.add(storage.path(value)) return media
def get_used_media()
Get media which are still used in models
3.31974
3.229151
1.028054
if not exclude: exclude = [] media = set() for root, dirs, files in os.walk(six.text_type(settings.MEDIA_ROOT)): for name in files: path = os.path.abspath(os.path.join(root, name)) relpath = os.path.relpath(path, settings.MEDIA_ROOT) for e in exclude: if re.match(r'^%s$' % re.escape(e).replace('\\*', '.*'), relpath): break else: media.add(path) return media
def get_all_media(exclude=None)
Get all media from MEDIA_ROOT
2.316673
2.200781
1.052659
if not exclude: exclude = [] all_media = get_all_media(exclude) used_media = get_used_media() return all_media - used_media
def get_unused_media(exclude=None)
Get media which are not used in models
2.983315
2.799623
1.065613
self.send_createCluster(hzVersion, xmlconfig) return self.recv_createCluster()
def createCluster(self, hzVersion, xmlconfig)
Parameters: - hzVersion - xmlconfig
3.760859
2.473126
1.520691
self.send_shutdownMember(clusterId, memberId) return self.recv_shutdownMember()
def shutdownMember(self, clusterId, memberId)
Parameters: - clusterId - memberId
2.463148
2.289024
1.076069
self.send_terminateMember(clusterId, memberId) return self.recv_terminateMember()
def terminateMember(self, clusterId, memberId)
Parameters: - clusterId - memberId
2.451903
2.378609
1.030814
self.send_suspendMember(clusterId, memberId) return self.recv_suspendMember()
def suspendMember(self, clusterId, memberId)
Parameters: - clusterId - memberId
2.566724
2.44152
1.051281
self.send_resumeMember(clusterId, memberId) return self.recv_resumeMember()
def resumeMember(self, clusterId, memberId)
Parameters: - clusterId - memberId
2.576551
2.361135
1.091234
self.send_mergeMemberToCluster(clusterId, memberId) return self.recv_mergeMemberToCluster()
def mergeMemberToCluster(self, clusterId, memberId)
Parameters: - clusterId - memberId
2.382147
2.081883
1.144227
self.send_executeOnController(clusterId, script, lang) return self.recv_executeOnController()
def executeOnController(self, clusterId, script, lang)
Parameters: - clusterId - script - lang
2.489828
2.337214
1.065297
uniform1 = cspace_convert(color1, input_space, uniform_space) uniform2 = cspace_convert(color2, input_space, uniform_space) return np.sqrt(np.sum((uniform1 - uniform2) ** 2, axis=-1))
def deltaE(color1, color2, input_space="sRGB1", uniform_space="CAM02-UCS")
Computes the :math:`\Delta E` distance between pairs of colors. :param input_space: The space the colors start out in. Can be anything recognized by :func:`cspace_convert`. Default: "sRGB1" :param uniform_space: Which space to perform the distance measurement in. This should be a uniform space like CAM02-UCS where Euclidean distance approximates similarity judgements, because otherwise the results of this function won't be very meaningful, but in fact any color space known to :func:`cspace_convert` will be accepted. By default, computes the euclidean distance in CAM02-UCS :math:`J'a'b'` space (thus giving :math:`\Delta E'`); for details, see :cite:`CAM02-UCS`. If you want the classic :math:`\Delta E^*_{ab}` defined by CIE 1976, use ``uniform_space="CIELab"``. Other good choices include ``"CAM02-LCD"`` and ``"CAM02-SCD"``. This function has no ability to perform :math:`\Delta E` calculations like CIEDE2000 that are not based on euclidean distances. This function is vectorized, i.e., color1, color2 may be arrays with shape (..., 3), in which case we compute the distance between corresponding pairs of colors.
2.211166
2.174211
1.016997
XYZ100 = np.asarray(XYZ100, dtype=float) # this is broadcasting matrix * array-of-vectors, where the vector is the # last dim RGB_linear = np.einsum("...ij,...j->...i", XYZ100_to_sRGB1_matrix, XYZ100 / 100) return RGB_linear
def XYZ100_to_sRGB1_linear(XYZ100)
Convert XYZ to linear sRGB, where XYZ is normalized so that reference white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear sRGB has a linear relationship to actual light, so it is an appropriate space for simulating light (e.g. for alpha blending).
4.090952
4.291858
0.953189
sRGB1 = np.asarray(sRGB1, dtype=float) sRGB1_linear = C_linear(sRGB1) return sRGB1_linear
def sRGB1_to_sRGB1_linear(sRGB1)
Convert sRGB (as floats in the 0-to-1 range) to linear sRGB.
2.964582
2.823357
1.05002
start = norm_cspace_id(start) end = norm_cspace_id(end) return GRAPH.get_transform(start, end)
def cspace_converter(start, end)
Returns a function for converting from colorspace ``start`` to colorspace ``end``. E.g., these are equivalent:: out = cspace_convert(arr, start, end) :: start_to_end_fn = cspace_converter(start, end) out = start_to_end_fn(arr) If you are doing a large number of conversions between the same pair of spaces, then calling this function once and then using the returned function repeatedly will be slightly more efficient than calling :func:`cspace_convert` repeatedly. But I wouldn't bother unless you know that this is a bottleneck for you, or it simplifies your code.
5.480732
8.940104
0.61305
converter = cspace_converter(start, end) return converter(arr)
def cspace_convert(arr, start, end)
Converts the colors in ``arr`` from colorspace ``start`` to colorspace ``end``. :param arr: An array-like of colors. :param start, end: Any supported colorspace specifiers. See :ref:`supported-colorspaces` for details.
4.51137
16.455105
0.274162
if observer == "CIE 1931 2 deg": return np.asarray(cie1931[name], dtype=float) elif observer == "CIE 1964 10 deg": return np.asarray(cie1964[name], dtype=float) else: raise ValueError("observer must be 'CIE 1931 2 deg' or " "'CIE 1964 10 deg', not %s" % (observer,))
def standard_illuminant_XYZ100(name, observer="CIE 1931 2 deg")
Takes a string naming a standard illuminant, and returns its XYZ coordinates (normalized to Y = 100). We currently have the following standard illuminants in our database: * ``"A"`` * ``"C"`` * ``"D50"`` * ``"D55"`` * ``"D65"`` * ``"D75"`` If you need another that isn't on this list, then feel free to send a pull request. When in doubt, use D65: it's the whitepoint used by the sRGB standard (61966-2-1:1999) and ISO 10526:1999 says "D65 should be used in all colorimetric calculations requiring representative daylight, unless there are specific reasons for using a different illuminant". By default, we return points in the XYZ space defined by the CIE 1931 2 degree standard observer. By specifying ``observer="CIE 1964 10 deg"``, you can instead get the whitepoint coordinates in XYZ space defined by the CIE 1964 10 degree observer. This is probably only useful if you have XYZ points you want to do calculations on that were somehow measured using the CIE 1964 color matching functions, perhaps via a spectrophotometer; consumer equipment (monitors, cameras, etc.) assumes the use of the CIE 1931 standard observer in all cases I know of.
1.911017
1.942561
0.983762
if isinstance(whitepoint, str): return standard_illuminant_XYZ100(whitepoint) else: whitepoint = np.asarray(whitepoint, dtype=float) if whitepoint.shape[-1] != 3: raise ValueError("Bad whitepoint shape") return whitepoint
def as_XYZ100_w(whitepoint)
A convenience function for getting whitepoints. ``whitepoint`` can be either a string naming a standard illuminant (see :func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly as an array-like of XYZ values. We internally call this function anywhere you have to specify a whitepoint (e.g. for CIECAM02 or CIELAB conversions). Always uses the "standard" 2 degree observer.
2.878629
2.345851
1.227115
assert 0 <= severity <= 100 fraction = severity % 10 low = int(severity - fraction) high = low + 10 assert low <= severity <= high low_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][low]) if severity == 100: # Don't try interpolating between 100 and 110, there is no 110... return low_matrix high_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][high]) return ((1 - fraction / 10.0) * low_matrix + fraction / 10.0 * high_matrix)
def machado_et_al_2009_matrix(cvd_type, severity)
Retrieve a matrix for simulating anomalous color vision. :param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly". :param severity: A value between 0 and 100. :returns: A 3x3 CVD simulation matrix as computed by Machado et al (2009). These matrices were downloaded from: http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html which is supplementary data from :cite:`Machado-CVD`. If severity is a multiple of 10, then simply returns the matrix from that webpage. For other severities, performs linear interpolation.
3.235425
2.87624
1.12488
rvchk = self.retval.checker if rvchk: def _checker(value): if not rvchk.check(value): raise self._type_error( "Incorrect return type in %s: expected %s got %s" % (self.name_bt, rvchk.name(), checker_for_type(type(value)).name()) ) else: def _checker(value): pass return _checker
def _make_retval_checker(self)
Create a function that checks the return value of the function.
4.749485
4.560753
1.041382
def _checker(*args, **kws): # Check if too many arguments are provided nargs = len(args) nnonvaargs = min(nargs, self._max_positional_args) if nargs > self._max_positional_args and self._ivararg is None: raise self._too_many_args_error(nargs) # Check if there are too few positional arguments (without defaults) if nargs < self._min_positional_args: missing = [p.name for p in self.params[nargs:self._min_positional_args] if p.name not in kws] # The "missing" arguments may still be provided as keywords, in # which case it's not an error at all. if missing: raise self._too_few_args_error(missing, "positional") # Check if there are too few required keyword arguments if self._required_kwonly_args: missing = [kw for kw in self._required_kwonly_args if kw not in kws] if missing: raise self._too_few_args_error(missing, "keyword") # Check types of positional arguments for i, argvalue in enumerate(args): param = self.params[i if i < self._max_positional_args else self._ivararg] if param.checker and not ( param.checker.check(argvalue) or param.has_default and (argvalue is param.default or argvalue == param.default) ): raise self._param_type_error(param, param.name, argvalue) # Check types of keyword arguments for argname, argvalue in kws.items(): argindex = self._iargs.get(argname) if argindex is not None and argindex < nnonvaargs: raise self._repeating_arg_error(argname) index = self._iargs.get(argname) if index is None: index = self._ivarkws if index is None: s = "%s got an unexpected keyword argument `%s`" % \ (self.name_bt, argname) raise self._type_error(s) param = self.params[index] if param.checker and not ( param.checker.check(argvalue) or param.has_default and (argvalue is param.default or argvalue == param.default) ): raise self._param_type_error(param, argname, argvalue) return _checker
def _make_args_checker(self)
Create a function that checks signature of the source function.
2.807571
2.776267
1.011276
try: if t is True: return true_checker if t is False: return false_checker checker = memoized_type_checkers.get(t) if checker is not None: return checker hashable = True except TypeError: # Exception may be raised if `t` is not hashable (e.g. a dict) hashable = False # The type checker needs to be created checker = _create_checker_for_type(t) if hashable: memoized_type_checkers[t] = checker return checker
def checker_for_type(t)
Return "checker" function for the given type `t`. This checker function will accept a single argument (of any type), and return True if the argument matches type `t`, or False otherwise. For example: chkr = checker_for_type(int) assert chkr.check(123) is True assert chkr.check("5") is False
3.268788
3.859056
0.847043
if val is None or val is True or val is False: return str(val) sval = repr(val) sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'") if len(sval) > maxlen: sval = sval[:maxlen - 4] + "..." + sval[-1] if notype: return sval else: tval = checker_for_type(type(val)).name() return "%s of type %s" % (sval, tval)
def _prepare_value(val, maxlen=50, notype=False)
Stringify value `val`, ensuring that it is not too long.
2.811239
2.743119
1.024833
if n % 10 == 1 and n % 100 != 11: return "%dst" % n if n % 10 == 2 and n % 100 != 12: return "%dnd" % n if n % 10 == 3 and n % 100 != 13: return "%drd" % n return "%dth" % n
def _nth_str(n)
Return posessive form of numeral `n`: 1st, 2nd, 3rd, etc.
1.496631
1.402049
1.06746
self.data.increaseClass(className) tokens = self.tokenizer.tokenize(text) for token in tokens: token = self.tokenizer.remove_stop_words(token) token = self.tokenizer.remove_punctuation(token) self.data.increaseToken(token, className)
def train(self, text, className)
enhances trained data using the given text and class
3.365457
3.324733
1.012249
def hid_device_path_exists(device_path, guid = None): # expecing HID devices if not guid: guid = winapi.GetHidGuid() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA) with winapi.DeviceInterfaceSetInfo(guid) as h_info: for interface_data in winapi.enum_device_interfaces(h_info, guid): test_device_path = winapi.get_device_path(h_info, interface_data, byref(info_data)) if test_device_path == device_path: return True # Not any device now with that path return False
Test if required device_path is still valid (HID device connected to host)
null
null
null
def find_all_hid_devices(): "Finds all HID devices connected to the system" # # From DDK documentation (finding and Opening HID collection): # After a user-mode application is loaded, it does the following sequence # of operations: # # * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass # devices. # # * Calls SetupDiGetClassDevs to obtain a handle to an opaque device # information set that describes the device interfaces supported by all # the HID collections currently installed in the system. The # application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE # in the Flags parameter passed to SetupDiGetClassDevs. # # * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the # available interface information. # # * Calls SetupDiGetDeviceInterfaceDetail to format interface information # for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure. # The device_path member of this structure contains the user-mode name # that the application uses with the Win32 function CreateFile to # obtain a file handle to a HID collection. # # get HID device class guid guid = winapi.GetHidGuid() # retrieve all the available interface information. results = [] required_size = DWORD() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA) with winapi.DeviceInterfaceSetInfo(guid) as h_info: for interface_data in winapi.enum_device_interfaces(h_info, guid): device_path = winapi.get_device_path(h_info, interface_data, byref(info_data)) parent_device = c_ulong() #get parent instance id (so we can discriminate on port) if setup_api.CM_Get_Parent(byref(parent_device), info_data.dev_inst, 0) != 0: #CR_SUCCESS = 0 parent_device.value = 0 #null #get unique instance id string required_size.value = 0 winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data), None, 0, byref(required_size) ) device_instance_id = create_unicode_buffer(required_size.value) if required_size.value > 0: winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data), device_instance_id, required_size, byref(required_size) ) hid_device = HidDevice(device_path, parent_device.value, device_instance_id.value ) else: hid_device = HidDevice(device_path, parent_device.value ) # add device to results, if not protected if hid_device.vendor_id: results.append(hid_device) return results
Finds all HID devices connected to the system
null
null
null
def show_hids(target_vid = 0, target_pid = 0, output = None): # first be kind with local encodings if not output: # beware your script should manage encodings output = sys.stdout # then the big cheese... from . import tools all_hids = None if target_vid: if target_pid: # both vendor and product Id provided device_filter = HidDeviceFilter(vendor_id = target_vid, product_id = target_pid) else: # only vendor id device_filter = HidDeviceFilter(vendor_id = target_vid) all_hids = device_filter.get_devices() else: all_hids = find_all_hid_devices() if all_hids: print("Found HID class devices!, writting details...") for dev in all_hids: device_name = str(dev) output.write(device_name) output.write('\n\n Path: %s\n' % dev.device_path) output.write('\n Instance: %s\n' % dev.instance_id) output.write('\n Port (ID): %s\n' % dev.get_parent_instance_id()) output.write('\n Port (str):%s\n' % str(dev.get_parent_device())) # try: dev.open() tools.write_documentation(dev, output) finally: dev.close() print("done!") else: print("There's not any non system HID class device available")
Check all HID devices conected to PC hosts.
null
null
null
def get_devices_by_parent(self, hid_filter=None): all_devs = self.get_devices(hid_filter) dev_group = dict() for hid_device in all_devs: #keep a list of known devices matching parent device Ids parent_id = hid_device.get_parent_instance_id() device_set = dev_group.get(parent_id, []) device_set.append(hid_device) if parent_id not in dev_group: #add new dev_group[parent_id] = device_set return dev_group
Group devices returned from filter query in order \ by devcice parent id.
null
null
null
def get_devices(self, hid_filter = None): if not hid_filter: #empty list or called without any parameters if type(hid_filter) == type(None): #request to query connected devices hid_filter = find_all_hid_devices() else: return hid_filter #initially all accepted results = {}.fromkeys(hid_filter) #the filter parameters validating_attributes = list(self.filter_params.keys()) #first filter out restricted access devices if not len(results): return {} for device in list(results.keys()): if not device.is_active(): del results[device] if not len(results): return {} #filter out for item in validating_attributes: if item.endswith("_includes"): item = item[:-len("_includes")] elif item.endswith("_mask"): item = item[:-len("_mask")] elif item +"_mask" in self.filter_params or item + "_includes" \ in self.filter_params: continue # value mask or string search is being queried elif item not in HidDevice.filter_attributes: continue # field does not exist sys.error.write(...) #start filtering out for device in list(results.keys()): if not hasattr(device, item): del results[device] elif item + "_mask" in validating_attributes: #masked value if getattr(device, item) & self.filter_params[item + \ "_mask"] != self.filter_params[item] \ & self.filter_params[item + "_mask"]: del results[device] elif item + "_includes" in validating_attributes: #subset item if self.filter_params[item + "_includes"] not in \ getattr(device, item): del results[device] else: #plain comparison if getattr(device, item) != self.filter_params[item]: del results[device] # return list(results.keys())
Filter a HID device list by current object parameters. Devices must match the all of the filtering parameters
null
null
null
def get_parent_device(self): if not self.parent_instance_id: return "" dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN dev_buffer = dev_buffer_type() try: if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer), MAX_DEVICE_ID_LEN, 0) == 0: #success return dev_buffer.value return "" finally: del dev_buffer del dev_buffer_type
Retreive parent device string id
null
null
null