如何在python中拦截特定的元组查找
我想知道,在将变量与硬编码值进行比较时,如何创建一个程序来动态检测代码中的以下情况,而不是使用枚举如何在python中拦截特定的元组查找,python,syntax,lint,inspect,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_accou
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'
通过将收款人\账户\类型
包装到一个类中,实现以下\uuuuuuuuuuuuuuuuuuuuuuuuuuuuu
:
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
但这不是我的选择,因为我有很多遗留代码我无法接触,但仍然需要报告。没有(非脆弱的)方法从运行的代码中检测到这一点。如果传入的值是'001'
,则无法知道它是函数外部的文本还是变量。如果您将BBAN
值设置为某个字符串子类,则可以执行此操作,因为这样您就可以检查该子类。@BrenBarn,请查看编辑扫描,您可以给出一个要更改的行为示例吗?重写\uuuu eq\uuuu
应该已经处理了中的blah('a','b')
情况,因为元组中的元素将按顺序进行相等比较。@BrenBarn,你完全正确<代码>\uuuu eq\uuu
也适用于元组查找。我想是我自己想出来的答案,你只是指给我看。谢谢