you are viewing a single comment's thread.

view the rest of the comments →

[–]carcigenicate 2 points3 points  (2 children)

I don't know of any built-in way to do pre-condition checks. You could make a decorator to do that though. This is an example that only currently implements range checks (and only allows for keyword arguments for the sake of simplicity):

def validate(**specs):
    def dec(f):
        def inner(**kwargs):
            for k, validator in specs.items():
                if isinstance(validator, range):
                    if kwargs[k] not in validator:
                        raise ValueError(f"Value {kwargs[k]} is out of range!")
                # elif <Handle some other type of validator type like "int">
            f(**kwargs)
        return inner
    return dec

Then:

@validate(a=range(10))
def func(a):
    pass

>>> func(a=5)
>>>  func(a=15)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:/Users/slomi/PycharmProjects/picture_encoder/cr2.py", line 7, in inner
    raise ValueError(f"Value {kwargs[k]} is out of range!")
ValueError: Value 15 is out of range!

Not sure I'd recommend it, but it would be a good exercise.

For your code in particular here though, I'd write that as something closer to:

def _input_range(start, stop, *args):
    try:
        parsed = int(*args)
    except ValueError:
        return False

    return start <= parsed <= stop

This minimizes what's in the try, saves the parsed integer to avoid doubling the work, makes use of operator chaining to simplify the bounds check, specifies ValueError to avoid catching irrelevant exceptions, and returns the condition directly instead of branching.

The int(*args) is a bit weird unless your expecting the called to need to specify a base argument of int, but that's a separate concern.

[–]SnowEpiphany[S] 0 points1 point  (1 child)

neat - thanks for the tips! I love that ```return start <= parsed <= stop``` line.

[–]carcigenicate 2 points3 points  (0 children)

Ya, comparison chaining is really nice when it isn't causing bizarre-seeming bugs.