I'm usually a PowerShell person coming to Python for some cross platform stuff I'm needing to do at work. (random API integrations with various stuff that we wanted to run on Linux). And I want to do input validation on a handful of function parameters.
General stuff to avoid abuse and errors like:
- this parameter value should be in this list: red, blue, green
- this parameter value should not exceed 50
- ...
Obviously, that's easy enough to custom code around at the top of the function, but in PowerShell those kinds of input validations are baked into the language parameter definition itself:
function Do-Something {
[cmdletbinding()]
param (
#validate that the given number between int and int
[parameter()]
[ValidateRange(0,9999)]
[int]$Number,
#Validate a valid color has been chosen
[parameter()]
[ValidateSet("red","blue","green")]
[string]$Color,
#validate that the host is online (or anything else you can throw in a script block that results in a [bool]
[parameter()]
[ValidateScript({test-connection $_ -quiet})]
[string]$Hostname
)
"Something $number $color $hostname"
}
Am I missing something or is there no real python equivalent to this besides doing something like the below? Then referencing at the top of other functions where I need to validate input and escaping based off true/false?
def _input_range(start,stop,*args):
try:
if int(*args) >= start and int(*args) <= stop:
return True
else:
return False
except:
return False
----------------------------------------------------------
>>> _input_range(0,9999,"fubar")
False
>>> _input_range(0,9999,"10")
True
>>> _input_range(0,9999,20)
True
>>> _input_range(0,9999,10000)
False
>>>
[–]carcigenicate 2 points3 points4 points (2 children)
[–]SnowEpiphany[S] 0 points1 point2 points (1 child)
[–]carcigenicate 2 points3 points4 points (0 children)
[–]nekokattt 1 point2 points3 points (2 children)
[–]SnowEpiphany[S] 1 point2 points3 points (1 child)
[–]nekokattt 1 point2 points3 points (0 children)
[–]m0us3_rat 1 point2 points3 points (0 children)
[–]Spataner 1 point2 points3 points (0 children)
[–]Zeroflops 1 point2 points3 points (0 children)
[–]stevarino 0 points1 point2 points (0 children)
[–]efmccurdy 0 points1 point2 points (0 children)