为了账号安全,请及时绑定邮箱和手机立即绑定

在 python 的 str() 函数的自定义 error_handler 中引用全局变量是否是可疑

在 python 的 str() 函数的自定义 error_handler 中引用全局变量是否是可疑

江户川乱折腾 2023-09-26 15:06:19
str()在函数的自定义 error_handler 中引用(或更改)使用 codecs.register_error() 设置的全局变量是坏/可疑/允许的做法吗?我正在尝试实现一个自定义的&ldquo;backslashreplace&rdquo;函数,除了反斜杠转义之外,还将结果括在单引号(')或双引号(&ldquo;)中,非常类似于 gnu 程序ls在--quoting-style=shell-escape.问题是,单引号或双引号之间的选择无法传输到错误处理程序。让它知道使用哪个的唯一方法是引用一个全局变量,该变量标记是否应该使用单/双引号。(我使用的是Python版本3.6.9)。这是一个示例程序:#!/usr/bin/env python3import codecs# in my program, quote varies between these two at runtime#quote = "'"quote = '"'def my_replace( e ):    global quote        # <-- global variable    if not isinstance( e, UnicodeDecodeError ):        raise TypeError( "don't know how to handle %r" % e )    x = []    for c in e.object[e.start:e.end]:        try:            if c == 0x93 or c == 0x94:                x.append( quote + ( "$'\\%o'" % c) + quote )        except KeyError:            return( None )    return( "".join(x), e.end )codecs.register_error( "my_replace", my_replace )s = b'61. \x93Gleich wie ein Hirsch begehret\x94, P.169_ IV. Variatio 3.flac's = str( s, 'utf-8', errors='my_replace' )print( quote + s + quote )
查看完整描述

1 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

使用全局变量来存储并稍后从一个或多个位置读取设置,对我来说看起来不错。特别是它做起来非常简单。


对于不同的想法,您是否考虑过为您的处理程序使用闭包,如下所示:


def outer(quote):

    settings = dict(quote=quote)

    def inner():

        print(settings['quote'])

    return inner


error_handler = outer("'")


# Then you register your error_handler...

# Later when called it remembers the settings

error_handler() # prints the simple quote

考虑到您的评论,使用类而不是闭包:


class QuotedErrorHandler:

    quote = "'"


    def handler(self, error):

        # do your thing

        print("Quote to use: {}".format(QuotedErrorHandler.quote))

        return error.upper()


QuotedErrorHandler.quote = '"'

my_handler = QuotedErrorHandler()

error_handler = my_handler.handler


print(error_handler("Some error"))

print(my_handler.quote)


查看完整回答
反对 回复 2023-09-26
  • 1 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号