If I design a function like
def f(a, b):
...
a must be in [1,2,3]. If I pass 4 to parameter a, it should raise an exception. Is there a pythonic way to limit the value range of a function argument?
Added
Please note, is there a more pythonic way to implement it? Not just a simple assert or if in.
For instance, decorator or maybe some syntactic sugar.
Yes, and also you can raise an exception if the input value is outside the desired range. For example, let's say you have a function called
fthat takes two integer parameters,aandb. To limit the range ofa, you can use an annotation likea: intto specify thatashould be an integer. Then, you can add anifstatement to check ifais within the desired range. If it's not, aValueErrorwill be raised with a specific error message. So, if you call the function with an invalid value fora, like4, it will raise an exception.update
In this new example, I created a decorator called
value_rangethat you can use to limit the range of a function argument, and it's super easy to use, just apply the decorator to your functionfand specify the range values you want, as you see if you pass a value outside that range, it'll raise aValueError. It's a really neat and pythonic way to keep things in check without messyassertorifstatements!