signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def check_author(author, **kwargs):
errors = []<EOL>authors = kwargs.get("<STR_LIT>")<EOL>if not authors:<EOL><INDENT>errors.append('<STR_LIT>' + _author_codes['<STR_LIT>'])<EOL>return errors<EOL><DEDENT>exclude_author_names = kwargs.get("<STR_LIT>")<EOL>if exclude_author_names and author in exclude_author_names:<EOL><INDENT>return []<EOL><DEDENT>path = ...
Check the presence of the author in the AUTHORS/THANKS files. Rules: - the author full name and email must appear in AUTHORS file :param authors: name of AUTHORS files :type authors: `list` :param path: path to the repository home :type path: str :return: errors :rtype: `list`
f3762:m10
def get_options(config=None):
if config is None:<EOL><INDENT>from . import config<EOL>config.get = lambda key, default=None: getattr(config, key, default)<EOL><DEDENT>base = {<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<...
Build the options from the config object.
f3762:m11
def run(self):
for msg in self.messages:<EOL><INDENT>col = getattr(msg, '<STR_LIT>', <NUM_LIT:0>)<EOL>yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__<EOL><DEDENT>
Yield the error messages.
f3762:c0:m0
def __init__(self, options):
super(_Report, self).__init__(options)<EOL>self.errors = []<EOL>
Initialize the reporter.
f3762:c1:m0
def error(self, line_number, offset, text, check):
code = super(_Report, self).error(line_number, offset, text, check)<EOL>if code:<EOL><INDENT>self.errors.append((line_number, offset + <NUM_LIT:1>, code, text, check))<EOL><DEDENT>
Run the checks and collect the errors.
f3762:c1:m1
@disable_on_env<EOL>def uuid(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if isinstance(value, uuid_.UUID):<EOL><INDENT>return value<EOL><DEDENT>try:<EOL><INDENT>value = uuid_.UUID(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>rai...
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...
f3771:m0
@disable_on_env<EOL>def string(value,<EOL>allow_empty = False,<EOL>coerce_value = False,<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>whitespace_padding = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>minimum_length = integer(minimum_length, allow_empty = True)<EOL>maximum_length = integer(maximum_length, allow_empty = True)<EOL>if coerce_value:<EOL><INDENT>v...
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...
f3771:m1
@disable_on_env<EOL>def iterable(value,<EOL>allow_empty = False,<EOL>forbid_literals = (str, bytes),<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif value is None:<EOL><INDENT>return None<EOL><DEDENT>minimum_length = integer(minimum_length, allow_empty = True, force_run = True) <EOL>maximum_length = integer(maximum_length, allow_empty = True, force_run =...
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. Def...
f3771:m2
@disable_on_env<EOL>def none(value,<EOL>allow_empty = False,<EOL>**kwargs):
if value is not None and not value and allow_empty:<EOL><INDENT>pass<EOL><DEDENT>elif (value is not None and not value) or value:<EOL><INDENT>raise errors.NotNoneError('<STR_LIT>')<EOL><DEDENT>return None<EOL>
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**...
f3771:m3
@disable_on_env<EOL>def not_empty(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and allow_empty:<EOL><INDENT>return None<EOL><DEDENT>elif not value:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>')<EOL><DEDENT>return value<EOL>
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 t...
f3771:m4
@disable_on_env<EOL>def variable_name(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>parse('<STR_LIT>' % value)<EOL><DEDENT>except (SyntaxError, ValueError, TypeError):<EOL><INDENT>raise errors.InvalidVariableNameError(<EOL>'<ST...
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_em...
f3771:m5
@disable_on_env<EOL>def dict(value,<EOL>allow_empty = False,<EOL>json_serializer = None,<EOL>**kwargs):
original_value = value<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if json_serializer is None:<EOL><INDENT>json_serializer = json_<EOL><DEDENT>if isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>v...
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...
f3771:m6
@disable_on_env<EOL>def json(value,<EOL>schema = None,<EOL>allow_empty = False,<EOL>json_serializer = None,<EOL>**kwargs):
original_value = value<EOL>original_schema = schema<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not json_serializer:<EOL><INDENT>json_serializer = json_<EOL><DEDENT>if isinstance(value, str):<EOL><...
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 ``sc...
f3771:m7
@disable_on_env<EOL>def date(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = True,<EOL>**kwargs):
<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>minimum = date(minimum, allow_empty = True, force_run = True) <EOL>maximum = date(maximum, allow_empty = True, force_run = True) ...
Validate that ``value`` is a valid date. :param value: The value to validate. :type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if...
f3771:m8
@disable_on_env<EOL>def datetime(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = True,<EOL>**kwargs):
<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>minimum = datetime(minimum, allow_empty = True, force_run = True) <EOL>maximum = datetime(maximum, allow_empty = True, force_run = True) ...
Validate that ``value`` is a valid datetime. .. caution:: If supplying a string, the string needs to be in an ISO 8601-format to pass validation. If it is not in an ISO 8601-format, validation will fail. :param value: The value to validate. :type value: :class:`str <python:str>` / :class:`dat...
f3771:m9
@disable_on_env<EOL>def time(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = True,<EOL>**kwargs):
<EOL>if not value and not allow_empty:<EOL><INDENT>if isinstance(value, datetime_.time):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT><DEDENT>elif not value:<EOL><INDENT>if not isinstance(value, datetime_.time):<EOL><INDENT>return None<EOL><DEDENT><DEDENT>...
Validate that ``value`` is a valid :class:`time <python:datetime.time>`. .. caution:: This validator will **always** return the time as timezone naive (effectively UTC). If ``value`` has a timezone / UTC offset applied, the validator will coerce the value returned back to UTC. :param value:...
f3771:m10
@disable_on_env<EOL>def timezone(value,<EOL>allow_empty = False,<EOL>positive = True,<EOL>**kwargs):
<EOL>original_value = value<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, tzinfo_types):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LI...
Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** verify whether the value is a timezone that actually exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``). For that kind of functionality, we recommend you utilize:...
f3771:m11
@disable_on_env<EOL>def numeric(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
if maximum is None:<EOL><INDENT>maximum = POSITIVE_INFINITY<EOL><DEDENT>else:<EOL><INDENT>maximum = numeric(maximum)<EOL><DEDENT>if minimum is None:<EOL><INDENT>minimum = NEGATIVE_INFINITY<EOL><DEDENT>else:<EOL><INDENT>minimum = numeric(minimum)<EOL><DEDENT>if value is None and not allow_empty:<EOL><INDENT>raise errors...
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 ``v...
f3771:m12
@disable_on_env<EOL>def integer(value,<EOL>allow_empty = False,<EOL>coerce_value = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>base = <NUM_LIT:10>,<EOL>**kwargs):
value = numeric(value, <EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>force_run = True)<EOL>if value is not None and hasattr(value, '<STR_LIT>'):<EOL><INDENT>if value.is_integer():<EOL><INDENT>return int(value)<EOL><DEDENT><DEDENT>i...
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>`...
f3771:m13
@disable_on_env<EOL>def float(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
try:<EOL><INDENT>value = _numeric_coercion(value,<EOL>coercion_function = float_,<EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum)<EOL><DEDENT>except (errors.EmptyValueError,<EOL>errors.CannotCoerceError,<EOL>errors.MinimumValueError,<EOL>errors.MaximumValueError) as error:<EOL><INDENT>raise...
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.EmptyValueErro...
f3771:m14
@disable_on_env<EOL>def fraction(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
try:<EOL><INDENT>value = _numeric_coercion(value,<EOL>coercion_function = fractions.Fraction,<EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum)<EOL><DEDENT>except (errors.EmptyValueError,<EOL>errors.CannotCoerceError,<EOL>errors.MinimumValueError,<EOL>errors.MaximumValueError) as error:<EOL><...
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.error...
f3771:m15
@disable_on_env<EOL>def decimal(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
if value is None and allow_empty:<EOL><INDENT>return None<EOL><DEDENT>elif value is None:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>value = decimal_.Decimal(value.strip())<EOL><DEDENT>except decimal_.InvalidOperation:<EOL><INDENT>raise erro...
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.Em...
f3771:m16
def _numeric_coercion(value,<EOL>coercion_function = None,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None):
if coercion_function is None:<EOL><INDENT>raise errors.CoercionFunctionEmptyError('<STR_LIT>')<EOL><DEDENT>elif not hasattr(coercion_function, '<STR_LIT>'):<EOL><INDENT>raise errors.NotCallableError('<STR_LIT>')<EOL><DEDENT>value = numeric(value, <EOL>allow_empty = a...
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:No...
f3771:m17
@disable_on_env<EOL>def bytesIO(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, io.BytesIO):<EOL><INDENT>raise errors.NotBytesIOError('<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value)))<EOL><DEDENT>return value<EOL>
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>` ...
f3771:m18
@disable_on_env<EOL>def stringIO(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, io.StringIO):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value)))<EOL><DEDENT>return value<EOL>
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>` ...
f3771:m19
@disable_on_env<EOL>def path(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if hasattr(os, '<STR_LIT>'):<EOL><INDENT>if not isinstance(value, (str, bytes, int, os.PathLike)): <EOL><INDENT>raise errors.NotPathlikeError...
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 em...
f3771:m20
@disable_on_env<EOL>def path_exists(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path(value, force_run = True) <EOL>if not os.path.exists(value):<EOL><INDENT>raise errors.PathExistsError('<STR_LI...
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.EmptyVal...
f3771:m21
@disable_on_env<EOL>def file_exists(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path_exists(value, force_run = True) <EOL>if not os.path.isfile(value):<EOL><INDENT>raise errors.NotAFileError('<STR_LIT>...
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>` ...
f3771:m22
@disable_on_env<EOL>def directory_exists(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path_exists(value, force_run = True) <EOL>if not os.path.isdir(value):<EOL><INDENT>raise errors.NotADirectoryError('<STR_...
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.EmptyValu...
f3771:m23
@disable_on_env<EOL>def readable(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = file_exists(value, force_run = True) <EOL>try:<EOL><INDENT>with open(value, mode='<STR_LIT:r>'):<EOL><INDENT>pass<EOL><DE...
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/Tim...
f3771:m24
@disable_on_env<EOL>def writeable(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path(value, force_run = True)<EOL>if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>is...
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 f...
f3771:m25
@disable_on_env<EOL>def executable(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = file_exists(value, force_run = True)<EOL>if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DE...
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...
f3771:m26
@disable_on_env<EOL>def email(value,<EOL>allow_empty = False,<EOL>**kwargs):
<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' % type(value))<EOL><DEDENT>if '<STR_LIT:@>' no...
Validate that ``value`` is a valid 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....
f3771:m27
@disable_on_env<EOL>def url(value,<EOL>allow_empty = False,<EOL>allow_special_ips = False,<EOL>**kwargs):
is_recursive = kwargs.pop('<STR_LIT>', False)<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' %...
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.ie...
f3771:m28
@disable_on_env<EOL>def domain(value,<EOL>allow_empty = False,<EOL>allow_ips = False,<EOL>**kwargs):
is_recursive = kwargs.pop('<STR_LIT>', False)<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' %...
Validate that ``value`` is a valid domain name. .. 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....
f3771:m29
@disable_on_env<EOL>def ip_address(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if is_py2 and value and isinstance(value, unicode):<EOL><INDENT>value = value.encode('<STR_LIT:utf-8>')<EOL><DEDENT>try:<EOL><INDENT>value = ipv6(value, force_r...
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). :pa...
f3771:m30
@disable_on_env<EOL>def ipv4(value, allow_empty = False):
if not value and allow_empty is False:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>components = value.split('<STR_LIT:.>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % va...
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`` i...
f3771:m31
@disable_on_env<EOL>def ipv6(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and allow_empty is False:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, str):<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % value)<EOL><DEDENT>value = value.lower().strip()<EOL>is_valid =...
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`` i...
f3771:m32
@disable_on_env<EOL>def mac_address(value,<EOL>allow_empty = False,<EOL>**kwargs):
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' % type(value))<EOL><DEDENT>if '<STR_LIT:->' in valu...
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 <vali...
f3771:m33
def disable_on_env(func):
@wraps(func)<EOL>def func_wrapper(*args, **kwargs):<EOL><INDENT>function_name = func.__name__<EOL>VALIDATORS_DISABLED = os.getenv('<STR_LIT>', '<STR_LIT>')<EOL>disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split('<STR_LIT:U+002C>')]<EOL>force_run = kwargs.get('<STR_LIT>', False)<EOL>try:<EOL><INDENT>valu...
Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, the ``value`` (first positional argument) passed to ``func``. If enabled, the result of ``func``.
f3775:m0
def disable_checker_on_env(func):
@wraps(func)<EOL>def func_wrapper(*args, **kwargs):<EOL><INDENT>function_name = func.__name__<EOL>CHECKERS_DISABLED = os.getenv('<STR_LIT>', '<STR_LIT>')<EOL>disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split('<STR_LIT:U+002C>')]<EOL>force_run = kwargs.get('<STR_LIT>', False)<EOL>if function_name in disab...
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``.
f3775:m1
@disable_checker_on_env<EOL>def is_type(obj,<EOL>type_,<EOL>**kwargs):
if not is_iterable(type_):<EOL><INDENT>type_ = [type_]<EOL><DEDENT>return_value = False<EOL>for check_for_type in type_:<EOL><INDENT>if isinstance(check_for_type, type):<EOL><INDENT>return_value = isinstance(obj, check_for_type)<EOL><DEDENT>elif obj.__class__.__name__ == check_for_type:<EOL><INDENT>return_value = True<...
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 us...
f3776:m0
def _check_base_classes(base_classes, check_for_type):
return_value = False<EOL>for base in base_classes:<EOL><INDENT>if base.__name__ == check_for_type:<EOL><INDENT>return_value = True<EOL>break<EOL><DEDENT>else:<EOL><INDENT>return_value = _check_base_classes(base.__bases__, check_for_type)<EOL>if return_value is True:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return ...
Indicate whether ``check_for_type`` exists in ``base_classes``.
f3776:m1
@disable_checker_on_env<EOL>def are_equivalent(*args, **kwargs):
if len(args) == <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>first_item = args[<NUM_LIT:0>]<EOL>for item in args[<NUM_LIT:1>:]:<EOL><INDENT>if type(item) != type(first_item): <EOL><INDENT>return False<EOL><DEDENT>if isinstance(item, dict):<EOL><INDENT>if not are_dicts_equivalent...
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 ch...
f3776:m2
@disable_checker_on_env<EOL>def are_dicts_equivalent(*args, **kwargs):
<EOL>if not args:<EOL><INDENT>return False<EOL><DEDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>if not all(is_dict(x) for x in args):<EOL><INDENT>return False<EOL><DEDENT>first_item = args[<NUM_LIT:0>]<EOL>for item in args[<NUM_LIT:1>:]:<EOL><INDENT>if len(item) != len(first_item):<EOL><INDENT>r...
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:...
f3776:m3
@disable_checker_on_env<EOL>def is_between(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
if minimum is None and maximum is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if value is None:<EOL><INDENT>return False<EOL><DEDENT>if minimum is not None and maximum is None:<EOL><INDENT>return value >= minimum<EOL><DEDENT>elif minimum is None and maximum is not None:<EOL><INDENT>return value <= maxim...
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 `...
f3776:m4
@disable_checker_on_env<EOL>def has_length(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
if minimum is None and maximum is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>length = len(value)<EOL>minimum = validators.numeric(minimum,<EOL>allow_empty = True)<EOL>maximum = validators.numeric(maximum,<EOL>allow_empty = True)<EOL>return is_between(length,<EOL>minimum = minimum,<EOL>maximum = maximum...
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__...
f3776:m5
@disable_checker_on_env<EOL>def is_dict(value, **kwargs):
if isinstance(value, dict):<EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>value = validators.dict(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 <py...
f3776:m6
@disable_checker_on_env<EOL>def is_json(value,<EOL>schema = None,<EOL>json_serializer = None,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.json(value,<EOL>schema = schema,<EOL>json_serializer = json_serializer,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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...
f3776:m7
@disable_checker_on_env<EOL>def is_string(value,<EOL>coerce_value = False,<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>whitespace_padding = False,<EOL>**kwargs):
if value is None:<EOL><INDENT>return False<EOL><DEDENT>minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs)<EOL>maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs)<EOL>if isinstance(value, basestring) and not value:<EOL><INDENT>if minimum_length and minimum_len...
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,...
f3776:m8
@disable_checker_on_env<EOL>def is_iterable(obj,<EOL>forbid_literals = (str, bytes),<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>**kwargs):
if obj is None:<EOL><INDENT>return False<EOL><DEDENT>if obj in forbid_literals:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>obj = validators.iterable(obj,<EOL>allow_empty = True,<EOL>forbid_literals = forbid_literals,<EOL>minimum_length = minimum_length,<EOL>maximum_length = maximum_length,<EOL>**kwargs)<EOL>...
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: ite...
f3776:m9
@disable_checker_on_env<EOL>def is_not_empty(value, **kwargs):
try:<EOL><INDENT>value = validators.not_empty(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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...
f3776:m10
@disable_checker_on_env<EOL>def is_none(value, allow_empty = False, **kwargs):
try:<EOL><INDENT>validators.none(value, allow_empty = allow_empty, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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`` ...
f3776:m11
@disable_checker_on_env<EOL>def is_variable_name(value, **kwargs):
try:<EOL><INDENT>validators.variable_name(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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: ``...
f3776:m12
@disable_checker_on_env<EOL>def is_callable(value, **kwargs):
return hasattr(value, '<STR_LIT>')<EOL>
Indicate whether ``value`` is callable (like a function, method, or class). :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...
f3776:m13
@disable_checker_on_env<EOL>def is_uuid(value, **kwargs):
try:<EOL><INDENT>validators.uuid(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 ...
f3776:m14
@disable_checker_on_env<EOL>def is_date(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = False,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.date(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>coerce_value = coerce_value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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>` / ...
f3776:m15
@disable_checker_on_env<EOL>def is_datetime(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = False,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.datetime(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>coerce_value = coerce_value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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.d...
f3776:m16
@disable_checker_on_env<EOL>def is_time(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = False,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.time(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>coerce_value = coerce_value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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_collec...
f3776:m17
@disable_checker_on_env<EOL>def is_timezone(value,<EOL>positive = True,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.timezone(value,<EOL>positive = positive,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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: ...
f3776:m18
@disable_checker_on_env<EOL>def is_numeric(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.numeric(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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...
f3776:m19
@disable_checker_on_env<EOL>def is_integer(value,<EOL>coerce_value = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>base = <NUM_LIT:10>,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.integer(value,<EOL>coerce_value = coerce_value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>base = base,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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...
f3776:m20
@disable_checker_on_env<EOL>def is_float(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.float(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 o...
f3776:m21
@disable_checker_on_env<EOL>def is_fraction(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.fraction(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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`...
f3776:m22
@disable_checker_on_env<EOL>def is_decimal(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
try:<EOL><INDENT>value = validators.decimal(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 ``valu...
f3776:m23
@disable_checker_on_env<EOL>def is_bytesIO(value, **kwargs):
return isinstance(value, io.BytesIO)<EOL>
Indicate whether ``value`` is a :class:`BytesIO <python:io.BytesIO>` object. .. note:: This checker will return ``True`` even if ``value`` is empty, so long as its type is a :class:`BytesIO <python:io.BytesIO>`. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, `...
f3776:m24
@disable_checker_on_env<EOL>def is_stringIO(value, **kwargs):
return isinstance(value, io.StringIO)<EOL>
Indicate whether ``value`` is a :class:`StringIO <python:io.StringIO>` object. .. note:: This checker will return ``True`` even if ``value`` is empty, so long as its type is a :class:`String <python:io.StringIO>`. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid,...
f3776:m25
@disable_checker_on_env<EOL>def is_pathlike(value, **kwargs):
try:<EOL><INDENT>value = validators.path(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 ...
f3776:m26
@disable_checker_on_env<EOL>def is_on_filesystem(value, **kwargs):
try:<EOL><INDENT>value = validators.path_exists(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 parameter...
f3776:m27
@disable_checker_on_env<EOL>def is_file(value, **kwargs):
try:<EOL><INDENT>value = validators.file_exists(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 ...
f3776:m28
@disable_checker_on_env<EOL>def is_directory(value, **kwargs):
try:<EOL><INDENT>value = validators.directory_exists(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 duplica...
f3776:m29
@disable_checker_on_env<EOL>def is_readable(value, **kwargs):
try:<EOL><INDENT>validators.readable(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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_ch...
f3776:m30
@disable_checker_on_env<EOL>def is_writeable(value,<EOL>**kwargs):
if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>validators.writeable(value,<EOL>allow_empty = False,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<...
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 sys...
f3776:m31
@disable_checker_on_env<EOL>def is_executable(value,<EOL>**kwargs):
if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>validators.executable(value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<...
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 s...
f3776:m32
@disable_checker_on_env<EOL>def is_email(value, **kwargs):
try:<EOL><INDENT>value = validators.email(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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. ...
f3776:m33
@disable_checker_on_env<EOL>def is_url(value, **kwargs):
try:<EOL><INDENT>value = validators.url(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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....
f3776:m34
@disable_checker_on_env<EOL>def is_domain(value, **kwargs):
try:<EOL><INDENT>value = validators.domain(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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. I...
f3776:m35
@disable_checker_on_env<EOL>def is_ip_address(value, **kwargs):
try:<EOL><INDENT>value = validators.ip_address(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 ...
f3776:m36
@disable_checker_on_env<EOL>def is_ipv4(value, **kwargs):
try:<EOL><INDENT>value = validators.ipv4(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 p...
f3776:m37
@disable_checker_on_env<EOL>def is_ipv6(value, **kwargs):
try:<EOL><INDENT>value = validators.ipv6(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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 p...
f3776:m38
@disable_checker_on_env<EOL>def is_mac_address(value, **kwargs):
try:<EOL><INDENT>value = validators.mac_address(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
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...
f3776:m39
@command<EOL>def install_completion(<EOL>shell: arg(choices=('<STR_LIT>', '<STR_LIT>'), help='<STR_LIT>'),<EOL>to: arg(help='<STR_LIT>') = None,<EOL>overwrite: '<STR_LIT>' = False):
if shell == '<STR_LIT>':<EOL><INDENT>source = '<STR_LIT>'<EOL>to = to or '<STR_LIT>'<EOL><DEDENT>elif shell == '<STR_LIT>':<EOL><INDENT>source = '<STR_LIT>'<EOL>to = to or '<STR_LIT>'<EOL><DEDENT>source = asset_path(source)<EOL>destination = os.path.expanduser(to)<EOL>if os.path.isdir(destination):<EOL><INDENT>destinat...
Install command line completion script. Currently, bash and fish are supported. The corresponding script will be copied to an appropriate directory. If the script already exists at that location, it will be overwritten by default.
f3779:m2
@command<EOL>def clean(verbose=False):
def rm(name):<EOL><INDENT>if os.path.isfile(name):<EOL><INDENT>os.remove(name)<EOL>if verbose:<EOL><INDENT>printer.info('<STR_LIT>', name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>printer.info('<STR_LIT>', name)<EOL><DEDENT><DEDENT><DEDENT>def rmdir(name):<EOL><INDENT>if os.path.isdir(name):<EOL><I...
Clean up. Removes: - ./build/ - ./dist/ - **/__pycache__ - **/*.py[co] Skips hidden directories.
f3779:m6
def parse_optional(self, string):
option_map = self.option_map<EOL>if string in option_map:<EOL><INDENT>return string, option_map[string], None<EOL><DEDENT>if '<STR_LIT:=>' in string:<EOL><INDENT>name, value = string.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>if name in option_map:<EOL><INDENT>return name, option_map[name], value<EOL><DEDENT><DEDENT>return ...
Parse string into name, option, and value (if possible). If the string is a known option name, the string, the corresponding option, and ``None`` will be returned. If the string has the form ``--option=<value>`` or ``-o=<value>``, it will be split on equals into an option name ...
f3786:c0:m7
def expand_short_options(self, argv):
new_argv = []<EOL>for arg in argv:<EOL><INDENT>result = self.parse_multi_short_option(arg)<EOL>new_argv.extend(result)<EOL><DEDENT>return new_argv<EOL>
Convert grouped short options like `-abc` to `-a, -b, -c`. This is necessary because we set ``allow_abbrev=False`` on the ``ArgumentParser`` in :prop:`self.arg_parser`. The argparse docs say ``allow_abbrev`` applies only to long options, but it also affects whether short options grouped...
f3786:c0:m8
def find_arg(self, name):
name = self.normalize_name(name)<EOL>return self.args.get(name)<EOL>
Find arg by normalized arg name or parameter name.
f3786:c0:m11
def find_parameter(self, name):
name = self.normalize_name(name)<EOL>arg = self.args.get(name)<EOL>return None if arg is None else arg.parameter<EOL>
Find parameter by name or normalized arg name.
f3786:c0:m12
@cached_property<EOL><INDENT>def args(self):<DEDENT>
params = self.parameters<EOL>args = OrderedDict()<EOL>args['<STR_LIT>'] = HelpArg(command=self)<EOL>normalize_name = self.normalize_name<EOL>get_arg_config = self.get_arg_config<EOL>get_short_option = self.get_short_option_for_arg<EOL>get_long_option = self.get_long_option_for_arg<EOL>get_inverse_option = self.get_inve...
Create args from function parameters.
f3786:c0:m20
@cached_property<EOL><INDENT>def option_map(self):<DEDENT>
option_map = OrderedDict()<EOL>for arg in self.args.values():<EOL><INDENT>for option in arg.options:<EOL><INDENT>option_map[option] = arg<EOL><DEDENT><DEDENT>return option_map<EOL>
Map command-line options to args.
f3786:c0:m25
@command<EOL>def copy_file(source, destination, follow_symlinks=True,<EOL>template: arg(type=bool_or(str), choices=('<STR_LIT>', '<STR_LIT:string>')) = False,<EOL>context=None):
if not template:<EOL><INDENT>return shutil.copy(source, destination, follow_symlinks=follow_symlinks)<EOL><DEDENT>if os.path.isdir(destination):<EOL><INDENT>destination = os.path.join(destination, os.path.basename(source))<EOL><DEDENT>with open(source) as source:<EOL><INDENT>contents = source.read()<EOL><DEDENT>if temp...
Copy source file to destination. The destination may be a file path or a directory. When it's a directory, the source file will be copied into the directory using the file's base name. When the source file is a template, ``context`` will be used as the template context. The supported template type...
f3787:m0
@command<EOL>def git_version(short: '<STR_LIT>' = True, show: '<STR_LIT>' = False):
result = local(<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>stdout='<STR_LIT>', stderr='<STR_LIT>', echo=False, raise_on_error=False)<EOL>if not result:<EOL><INDENT>return None<EOL><DEDENT>result = local(<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>stdout='<STR_LIT>', stderr='<STR_LIT>', echo=False, raise_on_...
Get tag associated with HEAD; fall back to SHA1. If HEAD is tagged, return the tag name; otherwise fall back to HEAD's short SHA1 hash. .. note:: Only annotated tags are considered. .. note:: The output isn't shown by default. To show it, pass the ``--show`` flag.
f3787:m1
@command<EOL>def local(args: arg(container=list),<EOL>cd=None,<EOL>environ: arg(type=dict) = None,<EOL>replace_env=False,<EOL>paths=(),<EOL>shell: arg(type=bool) = None,<EOL>stdout: arg(type=StreamOptions) = None,<EOL>stderr: arg(type=StreamOptions) = None,<EOL>echo=False,<EOL>raise_on_error=True,<EOL>dry_run=False,<EO...
if isinstance(args, str):<EOL><INDENT>if shell is None:<EOL><INDENT>shell = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>args = flatten_args(args, join=shell)<EOL><DEDENT>if cd:<EOL><INDENT>cd = abs_path(cd)<EOL>cd_passed = True<EOL><DEDENT>else:<EOL><INDENT>cd_passed = False<EOL><DEDENT>environ = {k: str(v) for k, v in ...
Run a local command via :func:`subprocess.run`. Args: args (list|str): A list of args or a shell command. cd (str): Working directory to change to first. environ (dict): Additional environment variables to pass to the subprocess. replace_env (bool): If set, only pass env...
f3787:m2
@command<EOL>def remote(cmd: arg(container=list),<EOL>host,<EOL>user=None,<EOL>port=None,<EOL>sudo=False,<EOL>run_as=None,<EOL>shell='<STR_LIT>',<EOL>cd=None,<EOL>environ: arg(container=dict) = None,<EOL>paths=(),<EOL>stdout: arg(type=StreamOptions) = None,<EOL>stderr: arg(type=StreamOptions) = None,<EOL>echo=False,<EO...
if not isinstance(cmd, str):<EOL><INDENT>cmd = flatten_args(cmd, join=True)<EOL><DEDENT>ssh_options = ['<STR_LIT>']<EOL>if isatty(sys.stdin):<EOL><INDENT>ssh_options.append('<STR_LIT>')<EOL><DEDENT>if port is not None:<EOL><INDENT>ssh_options.extend(('<STR_LIT>', port))<EOL><DEDENT>ssh_connection_str = '<STR_LIT>'.form...
Run a remote command via SSH. Runs a remote shell command using ``ssh`` in a subprocess like so: ssh -q [-t] [<user>@]<host> [sudo [-u <run_as>] -H] /bin/sh -c ' [cd <cd> &&] [export XYZ="xyz" &&] [export PATH="<path>" &&] <cmd> ' Args: cmd (list|str): The comm...
f3787:m3
@command<EOL>def sync(source,<EOL>destination,<EOL>host,<EOL>user=None,<EOL>sudo=False,<EOL>run_as=None,<EOL>options=('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'),<EOL>excludes=(),<EOL>exclude_from=None,<EOL>delete=False,<EOL>dry_run=False,<EOL>mode='<STR_LIT>',<EOL>quiet=True,<EOL>pull=False,<EOL>stdout: arg(type=StreamOpti...
source = abs_path(source, keep_slash=True)<EOL>destination = abs_path(destination, keep_slash=True)<EOL>connection_str = '<STR_LIT>'.format_map(locals()) if user else host<EOL>push = not pull<EOL>if sudo:<EOL><INDENT>rsync_path = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif run_as:<EOL><INDENT>rsync_path = ('<STR_LIT>',...
Sync files using rsync. By default, a local ``source`` is pushed to a remote ``destination``. To pull from a remote ``source`` to a local ``destination`` instead, pass ``pull=True``.
f3787:m4
def set_attrs(self, **attrs):
commands = tuple(self.values())<EOL>for name, value in attrs.items():<EOL><INDENT>for command in commands:<EOL><INDENT>setattr(command, name, value)<EOL><DEDENT><DEDENT>
Set the given attributes on *all* commands in collection.
f3788:c0:m3
def set_default_args(self, default_args):
for name, args in default_args.items():<EOL><INDENT>command = self[name]<EOL>command.default_args = default_args.get(command.name) or {}<EOL><DEDENT>
Set default args for commands in collection. Default args are used when the corresponding args aren't passed on the command line or in a direct call.
f3788:c0:m4
def abs_path(path, format_kwargs={}, relative_to=None, keep_slash=False):
if format_kwargs:<EOL><INDENT>path = path.format_map(format_kwargs)<EOL><DEDENT>has_slash = path.endswith(os.sep)<EOL>if os.path.isabs(path):<EOL><INDENT>path = os.path.normpath(path)<EOL><DEDENT>elif '<STR_LIT::>' in path:<EOL><INDENT>path = asset_path(path, keep_slash=False)<EOL><DEDENT>else:<EOL><INDENT>path = os.pa...
Get abs. path for ``path``. ``path`` may be a relative or absolute file system path or an asset path. If ``path`` is already an abs. path, it will be returned as is. Otherwise, it will be converted into a normalized abs. path. If ``relative_to`` is passed *and* ``path`` is not absolute, the path w...
f3790:m0
def asset_path(path, format_kwargs={}, keep_slash=False):
if format_kwargs:<EOL><INDENT>path = path.format_map(format_kwargs)<EOL><DEDENT>has_slash = path.endswith(os.sep)<EOL>if '<STR_LIT::>' in path:<EOL><INDENT>package_name, *rel_path = path.split('<STR_LIT::>', <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>package_name, rel_path = path, ()<EOL><DEDENT>try:<EOL><INDENT>packag...
Get absolute path to asset in package. ``path`` can be just a package name like 'package' or it can be a package name and a relative file system path like 'package:util'. If ``path`` ends with a slash, it will be stripped unless ``keep_slash`` is set (for use with ``rsync``, for example). >>> fil...
f3790:m1
def paths_to_str(paths, format_kwargs={}, delimiter=os.pathsep, asset_paths=False,<EOL>check_paths=False):
if not paths:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if isinstance(paths, str):<EOL><INDENT>paths = paths.split(delimiter)<EOL><DEDENT>processed_paths = []<EOL>for path in paths:<EOL><INDENT>original = path<EOL>path = path.format_map(format_kwargs)<EOL>if not os.path.isabs(path):<EOL><INDENT>if asset_paths and '<ST...
Convert ``paths`` to a single string. Args: paths (str|list): A string like "/a/path:/another/path" or a list of paths; may include absolute paths and/or asset paths; paths that are relative will be left relative format_kwargs (dict): Will be injected into each path ...
f3790:m2
def flatten_args(args: list, join=False, *, empty=(None, [], (), '<STR_LIT>')) -> list:
flat_args = []<EOL>non_empty_args = (arg for arg in args if arg not in empty)<EOL>for arg in non_empty_args:<EOL><INDENT>if isinstance(arg, (list, tuple)):<EOL><INDENT>flat_args.extend(flatten_args(arg))<EOL><DEDENT>else:<EOL><INDENT>flat_args.append(str(arg))<EOL><DEDENT><DEDENT>if join:<EOL><INDENT>join = '<STR_LIT:U...
Flatten args and remove empty items. Args: args: A list of items (typically but not necessarily strings), which may contain sub-lists, that will be flattened into a single list with empty items removed. Empty items include ``None`` and empty lists, tuples, and strings. ...
f3791:m1