在python'的自定义错误处理程序中引用全局变量是否值得怀疑;s str()函数?

在python'的自定义错误处理程序中引用全局变量是否值得怀疑;s str()函数?,python,global-variables,ls,custom-error-handling,Python,Global Variables,Ls,Custom Error Handling,在使用codecs.register\u error()设置的str()函数的自定义错误处理程序中引用(或更改)全局变量是错误的/可疑的/允许的做法吗? (见附件) 我正在尝试实现一个定制的“反斜杠替换”函数,该函数除了反斜杠转义外,还将结果包装为单引号(')或双引号(“),非常类似于gnuls程序在--quoting style=shell转义时对文件名所做的操作 问题是,单引号或双引号之间的选择无法传输到错误处理程序。让它知道使用哪一个的唯一方法是,它引用一个全局变量,该变量标记是否应使用单

在使用codecs.register\u error()设置的
str()
函数的自定义错误处理程序中引用(或更改)全局变量是错误的/可疑的/允许的做法吗? (见附件)

我正在尝试实现一个定制的“反斜杠替换”函数,该函数除了反斜杠转义外,还将结果包装为单引号(')或双引号(“),非常类似于gnu
ls
程序在
--quoting style=shell转义时对文件名所做的操作

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

(我使用的是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 )
!/usr/bin/env python3
导入编解码器
#在我的程序中,在运行时,这两个变量之间的引号是不同的
#quote=“””
引号=“”
def my_更换(e):

全局引号#在我看来,使用一个全局变量仅仅存储并稍后从一个或多个位置读取设置是合适的。特别是考虑到这是非常简单的事情

对于另一个想法,您是否想过为处理程序使用闭包,如下所示:

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)

@谢谢。不,我没有,我一定会调查的。变量
quote
也将在后面的
print()
语句中使用,因此我将看看是否可以以一种不太复杂的方式实现这一切。我将在一两个小时内研究这一切。非常感谢您的帮助!“类”方法似乎是答案;完成了它,而且很优雅。再次感谢你。