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

str()在函数的自定义 error_handler 中引用(或更改)使用 codecs.register_error() 设置的全局变量是坏/可疑/允许的做法吗?

我正在尝试实现一个自定义的“backslashreplace”函数,除了反斜杠转义之外,还将结果括在单引号(')或双引号(“)中,非常类似于 gnu 程序ls--quoting-style=shell-escape.

问题是,单引号或双引号之间的选择无法传输到错误处理程序。让它知道使用哪个的唯一方法是引用一个全局变量,该变量标记是否应该使用单/双引号。

(我使用的是Python版本3.6.9)。

这是一个示例程序:

#!/usr/bin/env python3


import 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 )


江户川乱折腾
浏览 209回答 1
1回答

三国纷争

使用全局变量来存储并稍后从一个或多个位置读取设置,对我来说看起来不错。特别是它做起来非常简单。对于不同的想法,您是否考虑过为您的处理程序使用闭包,如下所示:def outer(quote):&nbsp; &nbsp; settings = dict(quote=quote)&nbsp; &nbsp; def inner():&nbsp; &nbsp; &nbsp; &nbsp; print(settings['quote'])&nbsp; &nbsp; return innererror_handler = outer("'")# Then you register your error_handler...# Later when called it remembers the settingserror_handler() # prints the simple quote考虑到您的评论,使用类而不是闭包:class QuotedErrorHandler:&nbsp; &nbsp; quote = "'"&nbsp; &nbsp; def handler(self, error):&nbsp; &nbsp; &nbsp; &nbsp; # do your thing&nbsp; &nbsp; &nbsp; &nbsp; print("Quote to use: {}".format(QuotedErrorHandler.quote))&nbsp; &nbsp; &nbsp; &nbsp; return error.upper()QuotedErrorHandler.quote = '"'my_handler = QuotedErrorHandler()error_handler = my_handler.handlerprint(error_handler("Some error"))print(my_handler.quote)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python