【问题标题】:isinstance: How to manage set classes betterisinstance:如何更好地管理集合类
【发布时间】:2017-12-09 21:55:07
【问题描述】:

在编写一些调试 python 时,我似乎创建了一些我想清理的丑陋代码。

这里是完整的函数:

def debug(message, variable=None):
    if variable and DEBUG:
        print("\n" + str(type(variable)))
        try:
            if isinstance(variable, (list, dict, 'OrderedDict')):
                variable = json.dumps(
                    variable,
                    indent=4,
                    sort_keys=True
                )
        except TypeError:
            if isinstance(variable, (list, dict)):
                variable = json.dumps(
                    variable,
                    indent=4,
                    sort_keys=True
                )

    if DEBUG:
        if variable:
            print(message + str(variable) + "\n")
        else:
            print("\n" + message)

我特别鄙视我的 try-except 语句,因为我不仅在重复代码,而且如果我遇到另一个字典类(如请求标头中的 CaseInsensitiveDict),我想在调试输出期间很好地打印我将不得不嵌套 try-except 语句。

有没有一种方法可以检查 type(variable) 是否类似于 *dict**list* 然后在创建用于 isinstance 的元组时添加它?

【问题讨论】:

  • 'OrderedDict' 不是有效类型,它是一个字符串
  • 您的代码引发异常的唯一原因是您在isinstance() 调用中使用了字符串作为类型。没有理由在这里嵌套任何类型错误。
  • 您似乎可以使用logging 模块来处理大部分此类逻辑。也不清楚为什么您会检查实例并仍然期望TypeError 是可能的。
  • 感谢您与我们联系。当使用xmltodict 时,它是一个集合类,当解析使用xmltodict.parse(xml_string) 设置的变量时,此代码的行为与预期相同。从我读过的内容来看,元组必须是类型或类。
  • 我将不得不检查我以前没有使用过的 logging 模块。

标签: python isinstance


【解决方案1】:

你想看@functools.singledispatch() construct;这使您可以委托特定功能来处理调试,键入类型:

from functools import singledispatch

def debug(message, variable=None):
    if not DEBUG:
        return
    variable = debug_display(variable)
    print('{}{}\n'.format(message, variable))

@singledispatch
def debug_display(variable):
    return str(variable)

@debug_display.register(type(None))
def _none_to_empty_string(_ignored):
    return ''

@debug_display.register(dict)
@debug_display.register(list)
@debug_display.register(OrderedDict)
def _as_json(variable):
    return json.dumps(
        variable,
        indent=4,
        sort_keys=True
    )

@debug_display.register(SomeOtherType)
def _handle_specific_type(variable):
    # handle custom types any way you need to with separate registrations
    return "{} -> {}".format(variable.spam, variable.ham)

singledispatch 知道如何为没有特定处理程序的子类委托;所以OrderedDict_as_json 处理程序处理,因为它是dict 的子类。

【讨论】:

  • 太棒了!感谢您的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多