Function guard for Python3
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.

Function guard for Python 3

Rationale and thoughts:



from funcguard import guard
def abs(a, _when = "a >= 0"):
    return a

def abs(a, _when = "a < 0"):
    return -a

assert abs(1) == abs(-1) == 1
def factorial(n): # no _when expression => default
   return 1

def factorial(n, _when = "n > 1"):
   return n * factorial(n - 1)

assert factorial(10) == 3628800
class TypeTeller:
    def typeof(value, _when = "isinstance(value, int)"):
        return int
    def typeof(value, _when = "isinstance(value, str)"):
        return str

assert TypeTeller.typeof(0) is int
TypeTeller.typeof(0.0) # throws
class AllowedProcessor:
    def __init__(self, allowed):
        self._allowed = allowed
    def process(self, value, _when = "value in self._allowed"):
        return "ok"
    def process(self, value): # no _when expression => default
        return "fail"

ap = AllowedProcessor({1, 2, 3})
assert ap.process(1) == "ok"
assert ap.process(0) == "fail"
guard.default_eval_args( # values to insert to all guards scopes
    office_hours = lambda: 9 <= < 18)

def at_work(*args, _when = "office_hours()", **kwargs):

def at_work(*args, **kwargs):
    print("come back tomorrow")

at_work() # either "welcome" or "come back tomorrow"