如何在python中拦截特定的元组查找

时间:2014-05-29 06:47:19

标签: python syntax lint inspect

我想知道在将变量与硬编码值进行比较而不是动态地使用枚举时,如何创建程序来检测代码中的以下情况?

class AccountType:
    BBAN = '000'
    IBAN = '001'
    UBAN = '002'
    LBAN = '003'

我想在下列情况下报告代码(将警告放入日志中):

payee_account_type = self.get_payee_account_type(rc)     # '001' for ex.
if payee_account_type in ('001', '002'):                 # Report on unsafe lookup
    print 'okay, but not sure about the codes, man'

鼓励人们使用以下方法:

payee_account_type = self.get_payee_account_type(rc)
if payee_account_type in (AccountType.IBAN, AccountType.UBAN):
    print 'do this for sure'

哪个更安全。


如下所示验证==!=支票不是问题:

if payee_account_type == '001':
    print 'codes again'

payee_account_type打包到一个类中,并执行以下__eq__

class Variant:
    def __init__(self, value):
        self._value = value

    def get_value(self):
        return self._value

class AccountType:
    BBAN = Variant('000')
    IBAN = Variant('001')
    UBAN = Variant('002')
    LBAN = Variant('003')

class AccountTypeWrapper(object):
    def __init__(self, account_type):
        self._account_type = account_type

    def __eq__(self, other):
        if isinstance(other, Variant):
            # Safe usage
            return self._account_type == other.get_value()

        # The value is hardcoded
        log.warning('Unsafe comparison. Use proper enumeration object')
        return self._account_type == other

但是如何处理元组查找?


我知道,我可以创建一个包含查找的约定方法,可以在其中进行检查:

if IbanUtils.account_type_in(account_type, AccountType.IBAN, AccountType.UBAN):
    pass

class IbanUtils(object):
    def account_type_in(self, account_type, *types_to_check):
        for type in types_to_check:
            if not isinstance(type, Variant):
                log.warning('Unsafe usage')

            return account_type in types_to_check

但它不是我的选择,因为我有很多我无法触及的遗留代码,但仍然需要报告。

0 个答案:

没有答案