Skip to content

Repository files navigation

pyvalid

https://travis-ci.org/uzumaxy/pyvalid.svg?branch=master:alt:Travis(.org)

https://img.shields.io/codecov/c/github/uzumaxy/pyvalid.svg?style=plastic:alt:Codecov

Python validation tool for checking function's input parameters and return values. This module can be very helpful on the develop stage of the project, when control for accepted and returned function values is a one of most important things.

Module consists of two decorators: accepts and returns.

accepts(*accepted_arg_values, **accepted_kwargs_values)

A decorator for validating types and values of input parameters of a given function. You can pass the set of accepted types and values or validation function as decorator's input parameters. Validation process can raise the following exceptions:

  • pyvalid.InvalidArgumentNumberError — when the number or position of arguments supplied to a function is incorrect.
  • pyvalid.ArgumentValidationError — when the type of an argument to a function is not what it should be.

returns(*accepted_returns_values)

A decorator for validating the return value of a given function. You can pass the set of accepted types and values or validation function as a decorator's input parameters. Validation process can raise pyvalid.InvalidReturnType when the return value is not in the collection of supported values and types.

How to install

  • With PyPI: pip install -U pyvalid
  • Manually: python setup.py install

Example of usage

Function calc in example below has next limitations:

  • Can return only int or float value;
  • First parameter must be only of type str;
  • Second parameter must be of type int or equals to 2.0;
  • Third parameter must be of type int or float.
frompyvalidimportaccepts, returns@returns(int, float)@accepts(str, (int, 2.0), (int, float))defcalc(operator, val1, val2, val3):
expression='{v1} {op} {v2} {op} {v3}'.format(
op=operator,
v1=val1, v2=val2, v3=val3
)
returneval(expression)
# Output: 24.print(calc('*', 2, 3, 4))
# Output: 24.0.print(calc(operator='*', val1=2, val2=3.0, val3=4))
# Output: 24.0.print(calc('*', 2.0, 3, 4))
# Raise pyvalid.ArgumentValidationError exception,# because second argument has unsupported value.print(calc('*', 3.14, 3, 4))
# Raise pyvalid.InvalidReturnType exception,# because returns value is of type str.print(calc('*', 2, 3, '"4"'))

Here is an example of usage pyvalid module in context of classes. Pay attention to the method connect of the class SqlDriver. This method is a good demonstration of usage accepts decorator for functions with keyword arguments.

frompyvalidimportaccepts, returnsfromcollectionsimportIterableclassSqlDriver(object):
@returns(bool)@accepts(object, host=str, port=int, usr=str, pwd=str, db=[str, None])defconnect(self, **kwargs):
connection_string= \
'tsql -S {host} -p {port} -U {usr} -P {pwd} -D {db}'.format(**kwargs)
try:
print('Establishing connection: "{}"'.format(connection_string))
# Create connection..success=Trueexcept:
success=Falsereturnsuccess@returns(bool)defclose(self):
try:
print('Closing connection')
# Close connection..success=Trueexcept:
success=Falsereturnsuccess@returns(None, dict)@accepts(object, str, Iterable)defquery(self, sql, params=None):
try:
query_info='Processing request "{}"'.format(sql)
ifparamsisnotNone:
query_info+=' with following params: '+', '.join(params)
print(query_info)
# Process request..data=dict()
except:
data=Nonereturndatasql_driver=SqlDriver()
conn_params= {
'host': '8.8.8.8',
'port': 1433,
'usr': 'admin',
'pwd': 'Super_Mega_Strong_Password_2000',
'db': 'info_tech'
}
sql_driver.connect(**conn_params)
sql=r'SELECT * FROM ProgrammingLang'pl=sql_driver.query(sql)
sql=r'SELECT * FROM ProgrammingLang WHERE name=?'python_pl=sql_driver.query(sql, ('Python',))
sql_driver.close()

Following example with class User will show you how to use pyvalid module to validate some value with using validation function.

frompyvalidimportacceptsfrompyvalid.validatorsimportis_validatorclassUser(object):
classValidator(object):
unsafe_passwords= [
'111111', '000000', '123123',
'123456', '12345678', '1234567890',
'qwerty', 'sunshine', 'password',
]
@classmethod@is_validatordeflogin_checker(cls, login):
is_valid=isinstance(login, str) and1<=len(login) <=16ifis_valid:
forreg_userinUser.registered:
iflogin==reg_user.login:
is_valid=Falsebreakreturnis_valid@classmethod@is_validatordefpassword_checker(cls, password):
is_valid=isinstance(password, str) and \
(6<=len(password) <=32) and \
(passwordnotincls.unsafe_passwords)
returnis_validregistered=list()
def__init__(self, login, password):
self.__login=Noneself.login=loginself.__password=Noneself.password=passwordUser.registered.append(self)
@propertydeflogin(self):
returnself.__login@login.setter@accepts(object, Validator.login_checker)deflogin(self, value):
self.__login=value@propertydefpassword(self):
returnself.__password@password.setter@accepts(object, Validator.password_checker)defpassword(self, value):
self.__password=valueuser=User('admin', 'Super_Mega_Strong_Password_2000')
# Output: admin Super_Mega_Strong_Password_2000print(user.login, user.password)
# Raise pyvalid.ArgumentValidationError exception,# because User.Validator.password_checker method# returns False value.user.password='qwerty'# Raise pyvalid.ArgumentValidationError exception,# because User.Validator.login_checker method# returns False value.user=User('admin', 'Super_Mega_Strong_Password_2001')

License

Note that this project is distributed under the MIT License.

About

✅ Python values validator

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages