亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號