【问题标题】:Checking unwanted type change in Python检查 Python 中不需要的类型更改
【发布时间】:2013-06-11 08:16:32
【问题描述】:

我来自静态类型编程,我有兴趣了解动态类型编程背后的基本原理,以检查动态类型语言是否能更好地满足我的需求。

我读过鸭子编程背后的理论。我还读到单元测试(可取并用于静态类型编程)成为缺少编译时检查的动态语言的需求。

但是,我仍然害怕错过大局。特别是,如何检查变量类型意外更改的错误?

让我们用 Python 做一个非常简单的例子:

#! /usr/bin/env python

userid = 3
defaultname = "foo"

username = raw_input("Enter your name: ")
if username == defaultname:
    # Bug: here we meant userid...
    username = 2

# Here username can be either an int or a string
# depending on the branch taken.
import re
match_string = re.compile("oo")
if (match_string.match(username)):
        print "Match!"

Pylint、pychecker 和 pyflakes 不会对此问题发出警告。

处理此类错误的 Pythonic 方式是什么?

是否应该用 try/catch 包装代码?

【问题讨论】:

  • 在您的示例中,单元测试应该会发现您的错误并失败。将它包装在 try/except 中不会解决您的问题,您不应该使用这样的构造来检测逻辑错误。一个例外正是您在这种情况下想要的行为,因此您可以找到并解决问题。由于 Python 是动态类型的,你总会遇到这个问题,但同样,单元测试应该会解决这个问题。
  • 另外,这个stackoverflow.com/questions/1912476/… 刚刚在“相关”侧边栏中弹出。
  • 我明白了。所以单元测试是处理这类问题的正确方法(在这种情况下,我认为静态类型检查更可靠)。非常感谢。

标签: python pylint dynamic-typing pyflakes pychecker


【解决方案1】:

这不会在编译时为您提供检查,但正如您建议使用 try/catch 一样,我认为运行时检查也会有所帮助。

如果您使用类,您可以在__setattr__ 方法中挂钩您自己的类型检查。例如:

import datetime

# ------------------------------------------------------------------------------
# TypedObject
# ------------------------------------------------------------------------------
class TypedObject(object):     
    attr_types = {'id'         : int,
                  'start_time' : datetime.time,
                  'duration'   : float}

    __slots__ = attr_types.keys()

    # --------------------------------------------------------------------------
    # __setattr__
    # --------------------------------------------------------------------------
    def __setattr__(self, name, value):
        if name not in self.__slots__:
            raise AttributeError(
                "'%s' object has no attribute '%s'" 
                % (self.__class__.__name__, name))
        if type(value) is not self.attr_types[name]:
                raise TypeError(
                    "'%s' object attribute '%s' must be of type '%s'" 
                    % (self.__class__.__name__, name, 
                       self.attr_types[name].__name__))
        # call __setattr__ on parent class
        super(MyTypedObject, self).__setattr__(name, value)

这将导致:

>>> my_typed_object            = TypedObject()

>>> my_typed_object.id         = "XYZ"      # ERROR
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 28, in __setattr__
TypeError: 'MyTypedObject' object attribute 'id' must be of type 'int'

>>> my_typed_object.id         = 123        # OK

您可以继续使上面的 TypedObject 更通用,以便您的类可以继承它。

另一个(可能更好的)解决方案(指出here)可能是使用Entought Traits

【讨论】:

    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多