How to check function arguments type in Python All In One
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
demos
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
rpi-ws281x
API
def __init__(self, num, pin, freq_hz=800000, dma=10, invert=False, brightness=255, channel=0, strip_type=None, gamma=None):
"""Class to represent a SK6812/WS281x LED display. Num should be the
number of pixels in the display, and pin should be the GPIO pin connected
to the display signal line (must be a PWM pin like 18!). Optional
parameters are freq, the frequency of the display signal in hertz (default
800khz), dma, the DMA channel to use (default 10), invert, a boolean
specifying if the signal line should be inverted (default False), and
channel, the PWM channel to use (defaults to 0).
"""
https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/library/rpi_ws281x/rpi_ws281x.py#L41
bug demo ???
# ✅
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/examples/SK6812_white_test.py#LL34C66
refs
https://stackoverflow.com/questions/734368/type-checking-of-arguments-python
https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17452808.html
未经授权禁止转载,违者必究!