非 ASCII Python 标识符和反射率
Non-ASCII Python identifiers and reflectivity
我从 PEP 3131 了解到 Python 支持非 ASCII 标识符,尽管这不是最佳实践。
但是,我遇到了这种奇怪的行为,我的 </code> 标识符 (U+1D70F) 似乎自动转换为 <code>τ
(U+03C4)。
class Base(object):
def __init__(self):
self. = 5 # defined with U+1D70F
a = Base()
print(a.) # 5 # (U+1D70F)
print(a.τ) # 5 as well # (U+03C4) ? another way to access it?
d = a.__dict__ # {'τ': 5} # (U+03C4) ? seems converted
print(d['τ']) # 5 # (U+03C4) ? consistent with the conversion
print(d['']) # KeyError: '' # (U+1D70F) ?! unexpected!
这是预期的行为吗?为什么会发生这种静默转换?它与 NFKC 规范化有什么关系吗?我认为这只是为了规范地排序 Unicode 字符 sequences...
根据 the documentation on identifiers:
All identifiers are converted into the normal form NFKC while parsing;
comparison of identifiers is based on NFKC.
您可以看到 U+03C4 是使用 unicodedata
:
的合适结果
>>> import unicodedata
>>> unicodedata.normalize('NFKC', '')
'τ'
但是,此转换 不适用于 字符串文字,例如您用作字典键的字符串文字,因此它在字典中寻找未转换的字符只包含转换后的字符。
self. = 5 # implicitly converted to "self.τ = 5"
a. # implicitly converted to "a.τ"
d[''] # not converted
您可以看到类似的问题,例如与 getattr
:
一起使用的字符串文字
>>> getattr(a, '')
Traceback (most recent call last):
File "python", line 1, in <module>
AttributeError: 'Base' object has no attribute ''
>>> getattr(a, unicodedata.normalize('NFKD', ''))
5
我从 PEP 3131 了解到 Python 支持非 ASCII 标识符,尽管这不是最佳实践。
但是,我遇到了这种奇怪的行为,我的 </code> 标识符 (U+1D70F) 似乎自动转换为 <code>τ
(U+03C4)。
class Base(object):
def __init__(self):
self. = 5 # defined with U+1D70F
a = Base()
print(a.) # 5 # (U+1D70F)
print(a.τ) # 5 as well # (U+03C4) ? another way to access it?
d = a.__dict__ # {'τ': 5} # (U+03C4) ? seems converted
print(d['τ']) # 5 # (U+03C4) ? consistent with the conversion
print(d['']) # KeyError: '' # (U+1D70F) ?! unexpected!
这是预期的行为吗?为什么会发生这种静默转换?它与 NFKC 规范化有什么关系吗?我认为这只是为了规范地排序 Unicode 字符 sequences...
根据 the documentation on identifiers:
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.
您可以看到 U+03C4 是使用 unicodedata
:
>>> import unicodedata
>>> unicodedata.normalize('NFKC', '')
'τ'
但是,此转换 不适用于 字符串文字,例如您用作字典键的字符串文字,因此它在字典中寻找未转换的字符只包含转换后的字符。
self. = 5 # implicitly converted to "self.τ = 5"
a. # implicitly converted to "a.τ"
d[''] # not converted
您可以看到类似的问题,例如与 getattr
:
>>> getattr(a, '')
Traceback (most recent call last):
File "python", line 1, in <module>
AttributeError: 'Base' object has no attribute ''
>>> getattr(a, unicodedata.normalize('NFKD', ''))
5