在Python中强制/转换为正确类型的最佳位置 [英] Best place to coerce/convert to the right type in Python
问题描述
我对Python还是很陌生,我正在尝试适应它的动态类型.有时候,我有一个函数或一个类,它期望某种类型的参数,但是可以得到另一种可以强制执行的类型的值.例如,它可能期望为float
,但接收的是int或小数.或者它可能需要一个字符串,但是会收到一个定义__str__
特殊方法的对象.
I'm still fairly new to Python and I'm trying to get used to its dynamic typing. Sometimes I have a function or a class that expects a parameter of a certain type, but could get a value of another type that's coercible to it. For example, it might expect a float
but instead receive an int or a decimal. Or it might expect a string, but instead receive an object that defines the __str__
special method.
将参数强制为正确类型(及其原因)的最佳实践是什么?我是在函数/类中还是在调用方中进行的?如果在调用方中,是否还要在函数中进行检查?例如
What is the best practice for coercing the argument to the right type (and the reason for it)? Do I do it in the function/class or in the caller? If in the caller, do I also check for it in the function? Eg.
替代1:
def myfunc(takes_float):
myval = float(takes_float)
myfunc(5)
替代2:
def myfunc(takes_float):
myval = takes_float
myfunc(float(5))
替代3:
def myfunc(takes_float):
assert isinstance(takes_float, float)
myval = takes_float
myfunc(float(5))
我已经阅读了此答案和
I've already read this answer and this one and they say that checking types in Python is "bad", but I don't want to waste time tracking down very simple bugs which would be instantly picked up by the compiler in a statically typed language.
推荐答案
在您不可或缺的情况下,您会强迫"(也许-可能是个小问题).例如,假设您有一个函数,该函数需要一个浮点数并返回其正弦和余弦的和:
You "coerce" (perhaps -- it could be a noop) when it's indispensable for you to do so, and no earlier. For example, say you have a function that takes a float and returns the sum of its sine and cosine:
import math
def spc(x):
math.sin(x) + math.cos(x)
您应该在哪里强制" x浮动?答:根本没有地方-罪过和cos为您完成这项工作,例如:
Where should you "coerce" x to float? Answer: nowhere at all -- sin and cos do that job for you, e.g.:
>>> spc(decimal.Decimal('1.9'))
0.62301052082391117
那么什么时候强制(尽可能晚)强制进行 呢?例如,如果要在参数上调用字符串方法,则必须确保它是字符串-尝试调用例如在非字符串上的.lower
将不起作用,如果arg例如,len
可能会起作用,但与您期望的有所不同.一个列表(给您列表中的项数,而不是它表示为字符串的字符数),等等.
So when it is indispensable to coerce (as late as possible)? For example, if you want to call string methods on an argument, you do have to make sure it's a string -- trying to call e.g. .lower
on a non-string won't work, len
might work but do something different than you expect if the arg is e.g. a list (give you the number of items in the list, not the number of characters its representation as a string will take up), and so forth.
对于捕获错误,请考虑单元测试-半体面的单元测试将捕获静态键入会出现的所有错误,然后再发现一些错误.但是,这是一个不同的主题.
As for catching errors -- think unit tests -- semidecent unit tests will catch all errors static typing would, and then some. But, that's a different subject.
这篇关于在Python中强制/转换为正确类型的最佳位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!