How to check function arguments type in Python All In One
Python & argument type check
bug ❌
arguments type checker
#!/usr/bin/env python3
# coding: utf8
# arguments type checker ✅
def func(arg1: int, arg2: bool, arg3: str):
# arg1
if isinstance(arg1, int):
print("✅ arg1 =", arg1)
else:
print("type error ❌, arg1 =", arg1)
# arg2
if isinstance(arg2, bool):
print("✅ arg2 =", arg2)
else:
print("type error ❌, arg2 =", arg2)
# arg3
if isinstance(arg3, str):
print("✅ arg3 =", arg3)
else:
print("type error ❌, arg3 =", arg3)
print("\n")
if __name__ == "__main__":
func(255, False, "OK")
func(False, 255, "Error")
"""
$ py3 ./order-error-args.py
"""
$ py3 ./order-error-args.py
✅ arg1 = 255
✅ arg2 = False
✅ arg3 = OK
✅ arg1 = False
type error ❌, arg2 = 255
✅ arg3 = Error
bool
is instanceof int
???
False/True
=> 0/1
solution
#!/usr/bin/env python3
# coding: utf8
# arguments type checker ✅
def func(arg1: int, arg2: bool, arg3: str):
# arg1
if isinstance(arg1, int) and not isinstance(arg1, bool):
print("✅ arg1 =", arg1)
else:
print("type error ❌, arg1 =", arg1)
# arg2
if isinstance(arg2, bool):
print("✅ arg2 =", arg2)
else:
print("type error ❌, arg2 =", arg2)
# arg3
if isinstance(arg3, str):
print("✅ arg3 =", arg3)
else:
print("type error ❌, arg3 =", arg3)
print("\n")
if __name__ == "__main__":
func(255, False, "OK")
func(False, 255, "Error")
"""
$ py3 ./order-error-args.py
"""
$ py3 ./order-error-args.py
✅ arg1 = 255
✅ arg2 = False
✅ arg3 = OK
type error ❌, arg1 = False
type error ❌, arg2 = 255
✅ arg3 = Error