Skip to content

Use builtin guard clauses, and easily create custom guard clauses to improve code quality in python

License

Notifications You must be signed in to change notification settings

RoeiOhayon/Guardian

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Guardian Logo

Python PyPI PyPI Tweet

Guardian

A Guard Clause is a validation of information used to avoid errors during execution, and enables to "fail fast".
This package provides:

  • Function decorator guard clauses (All function arguments will be checked)
  • General use case guard clauses
  • Ability to create custom guard clauses

Install

pip install guardian-python

Usage

from guardian import guard


@guard.none()
def buy_item(username: str, user_repository: UserRepository, product_repository: ProductRepository):
    guard.not_alphabetic(username)
    ...

Supported Guard Clauses

  • numbers: zero, not_negative, not_positive, in_range, out_of_range
  • strings: matches_regex, not_matches_regex, whitespace, uppercase, lowercase, not_numeric, not_alphabetic, not_alphanumeric, empty_or_whitespace
  • dates: in_date_range, out_of_date_range, before, after
  • general: none, contains, equals, empty (list, str, tuple...)

Create a Custom Guard

custom_guard.py:

from guardian import Guard

dead = Guard(name="dead", predicate=lambda v: v.HP + v.armor <= 0, description="Don't Perform if dead")
alive = Guard(name="alive", predicate=lambda v: v.HP + v.armor > 0, description="Don't Perform if alive")

main.py:

import custom_guard

@custom_guard.dead()
def shoot(enemy: Enemy):
  ...

@custom_guard.alive()
def revive(player: Player):
  ... 

Additional Parameters

  • property: extracts property from objects
  • key: get value at key
  • transformer: function to extract wanted data to guard against
@guard.none(property="name")
def login(user: User):
  # if user.name is None an exception will be thrown

@guard.none(key="name")
def login(user: dict):
  # if user["name"] is None an exception will be thrown

@guard.none(transformer=lambda v: v.name)
def login(user: User):
  # if user.name is None an exception will be thrown

More Code Examples:

guard.matches_regex(".*el$")
def greet_user(username: str):
  # username = "Daniel" will throw an exception
  # username = "John" won't throw an exception
  ...

# Alternatively you can use:
def greet_user(username: str):
  guard.matches_regex(username, ".*el$")
  ...

@guard.out_of_range([0, 255])
def rgb_to_hsv(r: int, g: int, b: int) -> Tuple[int, int, int]:
  ...

Feel free to give a ⭐ if you enjoy using this project 😊

About

Use builtin guard clauses, and easily create custom guard clauses to improve code quality in python

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages