在 IDLE 中更改数字表示

Changing number representation in IDLE

我在日常工作中经常使用 Python IDLE,主要是为了编写简短的脚本以及作为一个功能强大且方便的计算器。

我通常需要使用不同的数字基数(主要是十进制、十六进制、二进制,较少使用八进制和其他基数。)

我知道使用 int()hex()bin()oct() 是从一个碱基移动到另一个碱基并添加前缀 integer literals 的便捷方法使用正确的前缀是表示数字的另一种方式。

我发现必须在函数中进行计算只是为了在正确的基数中查看结果非常不方便(hex() 和类似函数的结果输出是一个字符串),所以我我试图实现的是拥有一个函数(或者可能是一个语句?)将内部 IDLE 数字表示设置为已知基数(2、8、10、16)。

示例:

>>> repr_hex() # from now on, all number are considered hexadecimal, in input and in output

>>> 10 # 16 in dec
>>> 0x10 # now output is also in hexadecimal

>>> 1e + 2 
>>> 0x20

# override should be possible with integer literal prefixes
# 0x: hex ; 0b: bin ; 0n: dec ; 0o: oct
>>> 0b111 + 10 + 0n10 # dec : 7 + 16 + 10
>>> 0x21 # 33 dec

# still possible to override output representation temporarily with a conversion function
>>> conv(_, 10) # conv(x, output_base, current_base=internal_base)
>>> 0n33
>>> conv(_, 2) # use prefix of previous output to set current_base to 10
>>> 0b100001
>>> conv(10, 8, 16) # convert 10 to base 8 (10 is in base 16: 0x10)
>>> 0o20

>>> repr_dec() # switch to base 10, in input and in output
>>> _
>>> 0n16
>>> 10 + 10
>>> 0n20

实现这些功能似乎并不难,我不知道的是:

谢谢。

IDLE 没有数字表示法。它将您输入的代码发送到 Python 解释器并显示作为响应发回的字符串。从这个意义上讲,IDLE写在Python中是无关紧要的。对于 Python 代码的任何 IDE 或 REPL 也是如此。

也就是说,CPython sys 模块有一个 displayhook 函数。对于 3.5:

>>> help(sys.displayhook)
Help on built-in function displayhook in module sys:

displayhook(...)
    displayhook(object) -> None

    Print an object to sys.stdout and also save it in builtins._

实际上应该是 __builtins__._,如下例所示。请注意,输入是任何 Python 对象。对于 IDLE,默认 sys.displayhookidlelib/rpc.py 中定义的函数。这是与您的问题相关的示例。

>>> def new_hook(ob):
    if type(ob) is int:
        ob = hex(ob)
    __builtins__._ = ob
    print(ob)


>>> sys.displayhook = new_hook
>>> 33
0x21
>>> 0x21
0x21

这为您提供了您所要求的更重要的一半。在 IDLE 中实际使用任何东西之前,我会查看默认版本以确保我没有遗漏任何东西。可以编写一个扩展来添加可以切换显示挂钩的菜单项。

Python 故意没有输入预处理器功能。 GvR 希望 .py 文件的内容始终是某些版本的参考手册中定义的 python 代码。

我考虑过在 IDLE 中添加一个 inputhook 的可能性,但是当 运行 来自编辑器的 .py 文件时,我不会允许它处于活动状态。如果为 Shell 添加了一个,我会将提示从“>>>”更改为其他内容,例如 'hex>' 或 'bin>'.

编辑: 当通过菜单选择或热键或键绑定明确请求时,还可以编写一个扩展来重写输入代码。或者可以编辑当前的 idlelib/ScriptBinding.py 来自动重写。我想过的钩子会让这更容易,但不会扩展现在可以做的事情。