-
Notifications
You must be signed in to change notification settings - Fork 0
decorators.require
sikvelsigma edited this page Aug 18, 2022
·
6 revisions
- decorator
require_condition
For usage in a class, let's you set a condition in which a method is allowed to be called
- decorator
once
Functions decorated with once either always return the result of the 1st call or raise an error if called a 2nd time
- decorator
limit
Functions decorated with limit are allowed to be called on set amount of times
from pyuseful.decorators.require import require_condition
class Test:
# this style definition checks if the bool() of var is True
require_ready = require_condition("ready")
# this style uses eval() to check condition ('self.a>=self.b' in this example)
require_big_a = require_condition("a", ">=self.b")
# you can ommit the first arg and just use `cond`, 'msg' let's you specify error message
require_big_b = require_condition(cond="self.b>=self.a", msg="'b' must be equal or bigger than 'a'")
def __init__(self):
self.ready = False
self.a = 0
self.b = 2
def set_ready(self):
self.ready = True
@require_ready
@require_big_b
def inc_a(self):
self.a += 1
@require_ready
@require_big_a
def inc_b(self):
self.b += 1
t = Test()
# t.inc_a() # bool(ready) == False -> will raise an error
t.set_ready()
t.inc_a() # b>=a == True -> a=1, b=2
# t.inc_b() # a>=b == False -> will raise an error
t.inc_a() # b>=a == True -> a=2, b=2
t.inc_b() # a>=b == True -> a=2, b=3from pyuseful.decorators.require import once
# will always return the 1st called value
@once
def fun1(a):
return a
# will raise an error on the 2nd call
@once(mode="error")
def fun2(a):
return a
print(fun1(1)) # will print '1'
print(fun1(2)) # will still print '1'
print(fun2(1)) # will print '1'
# print(fun2(2)) # this will raise an errorfrom pyuseful.decorators.require import limit
@limit(2)
def fun():
print("hi")
fun() # 1st call is allowed
fun() # 2nd call is allowed
# fun() # 3rd call, this will raise an error