{"id":18521771,"url":"https://github.com/simphotonics/gvalidate","last_synced_at":"2025-05-14T18:09:17.679Z","repository":{"id":57436423,"uuid":"391138811","full_name":"simphotonics/gvalidate","owner":"simphotonics","description":"Generic argument validation for Python using decorators.  ","archived":false,"fork":false,"pushed_at":"2021-12-04T21:40:45.000Z","size":109,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-02-17T05:25:15.847Z","etag":null,"topics":["decorator","generic-programming","python","python3","validation"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/gvalidate","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/simphotonics.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-07-30T17:06:59.000Z","updated_at":"2021-12-04T21:40:48.000Z","dependencies_parsed_at":"2022-09-09T20:31:31.232Z","dependency_job_id":null,"html_url":"https://github.com/simphotonics/gvalidate","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgvalidate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgvalidate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgvalidate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simphotonics%2Fgvalidate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/simphotonics","download_url":"https://codeload.github.com/simphotonics/gvalidate/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254198510,"owners_count":22030966,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decorator","generic-programming","python","python3","validation"],"created_at":"2024-11-06T17:27:33.367Z","updated_at":"2025-05-14T18:09:12.671Z","avatar_url":"https://github.com/simphotonics.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Generic Validation For Python\n[![Python](https://github.com/simphotonics/gvalidate/actions/workflows/python.yml/badge.svg)](https://github.com/simphotonics/gvalidate/actions/workflows/python.yml)\n[![docs](https://raw.githubusercontent.com/simphotonics/gvalidate/main/images/docs-badge.svg)](https://gvalidate.simphotonics.com)\n\nChecking the input arguments of a function is a common task.\nIt allows the software designer to stop the flow of execution if\nan error occured and to display information detailing the error.\n\nPython provides *decorators* that can be used to add extra\nfunctionality to a function. The package [`gvalidate`][gvalidate]\nprovides the function [`validate`][validate] that\ncan be used to easily create argument validating decorators\nwhile avoiding most of the\nrequired boilerplate.\n\n## Installation\n\nTo install the package [`gvalidate`][gvalidate] use the command:\n```Console\n$ pip install gvalidate\n```\n\n## Usage\n\nThis section demonstrates how to use the function [`validate`][validate]\nto define validation decorators.\n\n### 1. Generic Validation Decorators\n\nThe example below shows how to define a decorator that will validate\nthe arguments of the decorated function and\nraise an exception of type `ValueError` if any argument does not pass validation.\n\nThe most important ingredient is the function provided as `validator`.\nThis function must accept one argument (the one\nbeing validated) and return a boolean.\nIf it returns `False` validation fails.\nThe function [`validate`][validate] is generic in the sense that we\ncan pass any function with the required signature as a validator.\n\nIn the example shown below all arguments of the function `box_dimensions`\nare validated using a lambda function.\n``` python\nfrom gvalidate.generic_validators import validate\n\n@validate(validator = lambda x: x \u003e 0,\n          message='Dimensions must be positive.' # Optional, default: ''\n          error_type=ValueError,                 # Optional, default: ValueError\n          enable_warnings=True,                  # Optional, default: True\n          )\ndef box_dimensions(length, height, width):\n  pass\n```\n\nTo validate only `certain` function arguments these must\nbe passed as a tuple via the parameter `argument_names`.\nIn the example below only the arguments `length` and `height` are\nvalidated.\n``` python\nfrom gvalidate.generic_validators import validate\n\n@validate(validator = lambda x: x \u003e 0,\n          argument_names = ('length', 'height'),\n          message='Dimensions must be positive.' # Optional, default: ''\n          error_type=ValueError,                 # Optional, default: ValueError\n          enable_warnings=True,                  # Optional, default: True\n          )\ndef box_dimensions_2(length, height, width):\n  pass\n```\nNote: To validate a *single* argument one a string containing the argument name may\nspecified via the parameter `argument_names`.\n\nCalling the function `box_dimensions` with negative arguments\ncauses an exception to be raised:\n``` python\nbox_dimensions(-1, 10, 20)\n# ... stack trace will be printed here\nValueError: ('Invalid argument in function box_dimensions: length = -10.'\n             'Dimensions must be positive.')\n\n```\nThe argument `message` passed to the decorator is appended to the\nmessage attached to the exception. In the example above `message` was:\n'Dimensions must be positive'.\n\n### 2. Concrete Validation Decorators\n\nIn the example above, we defined a validating decorator on the spot\nusing the generic method [`validate`][validate].\nTo reuse a validating decorator one may define a separate function.\n\nIn the example below the decorator `validate_callable` checks if the\nspecified arguments are callable.\n```Python\ndef validate_callable(argument_names: tuple = (), enable_warnings=True):\n    '''\n    Raises an exception if any argument in `argument_names` is not callable.\n    '''\n    return validate(\n        validator=lambda input: callable(input),\n        argument_names = (),\n        message='Must be callable.',\n        enable_warnings=enable_warnings,\n        )\n\n# Using the decorator defined above.\n@validate_callable('callback')\ndef function_with_a_callback(id: int, callback: callable):\n    pass\n\n```\n\nReady made validation decorators can be found in the modules:\n\n- `function_validators`\n- `numerical_validators`\n- `string_validators`\n\n### 3. Disabling Warnings\n\nAny invalid argument name listed in the tuple `argument_names`\nwill be silently ignored if `enable_warnings` is explicitly set to `False`.\nConsider the function below:\n``` python\nfrom gvalidate.generic_validators import validate\n\n@validate(argument_names = ('aeg',),\n             validator = lambda x: x \u003e 0,\n             message='Age must be positive.',\n             enable_warnings=False\n             )\ndef person_data(age, name):\n  pass\n```\nCalling the function with the arguments: `person_data(age = -10, name = 'Anna')`\nwill *pass* validation since the argument name `aeg` specified\nin the decorator does not exist.\n\n## Nested Validators\n\nSeveral decorators performing validation\nmay be applied to the same function.\nIn that case, validation starts with the top-most decorator.\nStacking decorators allows fine grained validation.\n\nIn the example below, we check that `length` is positive and `callback` is callable:\n```Python\n@gv.validate_positive('length')\n@gv.validate_callable('callback')\ndef g(length, callback):\n    '''\n    Used to test nested validation decorators.\n    '''\n    pass\n```\n\nNote: Stacked decorators are in fact nested decorators. To allow\naccess to the signature of the decorated\nfunction from within nested decorators\n[`functools.wraps`](https://docs.python.org/3/library/functools.html#functools.wraps)\nwas used. For more details check out the implementation of [`validate`][validate].\n\n## Testing\n\nTo run the tests clone the project source code available at\n[`gvalidate`](https://github.com/simphotonics/gvalidate)\nusing the command:\n```\n$ git clone https://github.com/simphotonics/gvalidate.git\n```\nThe command above will create a directory called `gvalidate`.\nIt is recommended to create a separate environment before proceeding.\n\nThen navigate to the directory `gvalidate` and use the commands:\n```Console\n$ make init\n$ make test\n```\nThe first command will install [`pytest`][pytest] and the local package\n`gvalidate`. The second command\nwill run the unit tests located in the directory `tests`.\n\n## Contributing\n\nContributions are welcome. To add validators that are useful to you\nor other users please create a pull request or request to be added\nas a collaborator.\n\nThe following steps should be considered when creating a pull request:\n\n1. Add validators to existing modules for example `string_validators` or\n   alternatively create a new module.\n\n2. Document the added functions. Add a doc entry to the top of the module.\n   Add a doc entry to `__init__.py` if a new module was added.\n   Consider adding documentation to `README.md`.\n\n3. Add tests to unit test the added functions.\n\n\n## Features and bugs\n\nPlease file feature requests and bugs at the [issue tracker].\n\n\n[issue tracker]: https://github.com/simphotonics/gvalidate/issues\n\n[gvalidate]: https://github.com/simphotonics/gvalidate\n\n[pytest]: https://pypi.org/project/pytest/\n\n[validate]: https://gvalidate.simphotonics.com/reference/gvalidate/generic/#validate","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimphotonics%2Fgvalidate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsimphotonics%2Fgvalidate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimphotonics%2Fgvalidate/lists"}