Jon*_*anK 2 python types type-safety
在我最近的项目中,我遇到了一个问题,即某些值经常被误解.例如,我计算一个波作为两个波的总和(我需要两个振幅和两个相移),然后在4个点采样.我将这四个值的元组传递给不同的函数,但有时我错误地传递波参数而不是采样点.
这些错误很难找到,因为所有计算都没有任何错误,但在这种情况下,这些值完全没有意义,因此结果是错误的.
我现在想要的是某种语义类型.我想声明一个函数返回样本点而另一个函数等待样本点,并且我不会做任何会在没有立即出错的情况下与此声明冲突的事情.
有没有办法在python中这样做?
我建议实现特定的数据类型,以便能够区分具有相同结构的不同类型的信息.您可以简单地进行子类化list,然后在函数中的运行时进行一些类型检查:
class WaveParameter(list):
pass
class Point(list):
pass
# you can use them just like lists
point = Point([1, 2, 3, 4])
wp = WaveParameter([5, 6])
# of course all methods from list are inherited
wp.append(7)
wp.append(8)
# let's check them
print(point)
print(wp)
# type checking examples
print isinstance(point, Point)
print isinstance(wp, Point)
print isinstance(point, WaveParameter)
print isinstance(wp, WaveParameter)
Run Code Online (Sandbox Code Playgroud)
因此,您可以在函数中包含此类型检查,以确保将正确类型的数据传递给它:
def example_function_with_waveparameter(data):
if not isinstance(data, WaveParameter):
log.error("received wrong parameter type (%s instead WaveParameter)" %
type(data))
# and then do the stuff
Run Code Online (Sandbox Code Playgroud)
或者干脆assert:
def example_function_with_waveparameter(data):
assert(isinstance(data, WaveParameter))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
642 次 |
| 最近记录: |