测试输入是否格式良好的数字的最 Pythonic 方法是什么

发布于 2024-07-11 03:35:10 字数 349 浏览 8 评论 0原文

我有一个函数需要实数(整数或浮点数)作为其输入,并且我试图在对其进行数学运算之前验证该输入。

我的第一直觉是将输入转换为 try- except 块中的浮点数。

try:
   myinput = float(input)
except:
   raise ValueError("input is not a well-formed number")

我也可以调用 isinstance(mydata, (float, int, long) ) ,但“所有这些都可能是数字”的列表对我来说似乎有点不优雅。

最Pythonic的方法是什么? 还有另一个我忽略的选择吗?

I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.

My first instinct is to cast inputs as floats from within a try-except block.

try:
   myinput = float(input)
except:
   raise ValueError("input is not a well-formed number")

I could also call isinstance(mydata, (float, int, long) ) but the list of "all these could be numbers" seems a bit inelegant to me.

What's the most pythonic way of going about it? Is there another option I overlooked?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你列表最软的妹 2024-07-18 03:35:10

引用我的话多少我应该对我的 python 函数/方法进行输入验证吗?

对于总和、阶乘等计算,Python 的内置类型检查可以很好地完成。 计算最终将调用 add、mul 等类型,如果它们中断,它们无论如何都会抛出正确的异常。 通过强制执行您自己的检查,您可能会使其他工作输入无效。

因此,最好的选择是将类型检查留给 Python。 如果计算失败,Python的类型检查会给出异常,所以如果你自己做,你只是重复代码,这意味着你需要做更多的工作。

To quote myself from How much input validation should I be doing on my python functions/methods?:

For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling add, mul etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input.

Thus, the best option is to leave the type checking up to Python. If the calculation fails, Python's type checking will give an exception, so if you do it yourself, you just duplicate code which means more work on your behalf.

惟欲睡 2024-07-18 03:35:10

在 Python 2.6 和 3.0 中,添加了数字抽象数据类型的类型层次结构,因此您可以执行检查:

>>> import numbers
>>> isValid = isinstance(myinput , numbers.Real)

numbers.Real将匹配整数或浮点类型,但不匹配非数字类型或复数(使用numbers.Complex)。 它还会匹配有理数,但想必您也想包括这些。 即:

>>> [isinstance(x, numbers.Real) for x in [4, 4.5, "some string", 3+2j]]
[True, True, False, False]

不幸的是,这一切都是在 Python >=2.6 中进行的,因此如果您正在为 2.5 或更早版本进行开发,则不会有用。

In Python 2.6 and 3.0, a type hierarchy of numeric abstract data types has been added, so you could perform your check as:

>>> import numbers
>>> isValid = isinstance(myinput , numbers.Real)

numbers.Real will match integral or float type, but not non-numeric types, or complex numbers (use numbers.Complex for that). It'll also match rational numbers , but presumably you'd want to include those as well. ie:

>>> [isinstance(x, numbers.Real) for x in [4, 4.5, "some string", 3+2j]]
[True, True, False, False]

Unfortunately, this is all in Python >=2.6, so won't be useful if you're developing for 2.5 or earlier.

镜花水月 2024-07-18 03:35:10

也许您可以结合使用 assertisinstance 语句。
我认为像下面这样的方式更Pythonic,因为只要您的输入不符合您的要求,您就会抛出异常。 不幸的是,我没有看到比你的更好的有效数字定义。 也许有人会提出更好的主意。

number = (float, int, long)
assert isinstance(mydata, (float, int, long))

Maybe you can use a combination of assert and isinstance statements.
Something like the following is I think a more pythonic way, as you throw an exception whenever your inputs don't follow your requirements. Unfortunately I don't see any better definition of what is a valid number than yours. Maybe someone will come with a better idea.

number = (float, int, long)
assert isinstance(mydata, (float, int, long))
北方。的韩爷 2024-07-18 03:35:10

我不明白这个问题。

有两种语义截然不同的东西被作为“替代品”扔掉。

类型转换是一回事。 它适用于任何支持 __float__ 的对象,这些对象可以是各种各样的对象,其中很少有实际上是数字的。

try:
   myinput = float(input)
except:
   raise ValueError("input is not a well-formed number")
# at this point, input may not be numeric at all
# it may, however, have produced a numeric value

类型测试是另一回事。 这仅适用于作为特定类集的正确实例的对象。

isinstance(input, (float, int, long) )
# at this point, input is one of a known list of numeric types

下面是响应 float 的示例类,但仍然不是数字。

class MyStrangeThing( object ):
    def __init__( self, aString ):
        # Some fancy parsing 
    def __float__( self ):
        # extract some numeric value from my thing

“实数(整数或浮点数)”问题通常是无关紧要的。 许多东西都是“数字”的,可以在数字运算中使用,但不是整数或浮点数。 例如,您可能已经下载或创建了有理数包。

过度验证输入是没有意义的,除非您有一个不适用于某些类型的算法。 这些很少见,但有些计算需要整数,特别是这样它们可以进行整数除法和余数运算。 对于这些,您可能想要断言您的值是整数。

I don't get the question.

There are two things with wildly different semantics tossed around as "alternatives".

A type conversion is one thing. It works with any object that supports __float__, which can be quite a variety of objects, few of which are actually numeric.

try:
   myinput = float(input)
except:
   raise ValueError("input is not a well-formed number")
# at this point, input may not be numeric at all
# it may, however, have produced a numeric value

A type test is another thing. This works only with objects that are proper instances of a specific set of classes.

isinstance(input, (float, int, long) )
# at this point, input is one of a known list of numeric types

Here's the example class that responds to float, but is still not numeric.

class MyStrangeThing( object ):
    def __init__( self, aString ):
        # Some fancy parsing 
    def __float__( self ):
        # extract some numeric value from my thing

The question "real numbers (either integers or floats)" is generally irrelevant. Many things are "numeric" and can be used in a numeric operation but aren't ints or floats. For example, you may have downloaded or created a rational numbers package.

There's no point in overvalidating inputs, unless you have an algorithm that will not work with some types. These are rare, but some calculations require integers, specifically so they can do integer division and remainder operations. For those, you might want to assert that your values are ints.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文