[파이썬] `sys.__displayhook__`: 원본 디스플레이 훅

In Python, when you interactively execute code in the interpreter, the result of each expression is automatically printed to the console. This is made possible by the sys.displayhook mechanism. The sys.displayhook is a global variable that points to a function responsible for displaying the value of the last expression evaluated.

In this blog post, we will explore the sys.__displayhook__ attribute, which is the original display hook function used in Python.

What is a Display Hook?

The display hook is a Python feature that controls the output of expressions evaluated in the interactive console. Whenever a line of code is executed in the interpreter, the resulting value is passed to the display hook function for presentation.

By default in Python, the display hook function is responsible for assigning the value to the special variable _ and then printing it to the console. However, you can customize the display hook to change its behavior.

Accessing the Original Display Hook

The original display hook function can be accessed using the sys.__displayhook__ attribute. This attribute holds a reference to the original function used by Python to print the value of the last expression.

To access the original display hook, you need to import the sys module and access the __displayhook__ attribute:

import sys

original_display_hook = sys.__displayhook__

Customizing the Display Hook

You can customize the display hook function to modify the behavior of how values are displayed in the console. For example, you can implement custom formatting or redirect the output to a different stream.

To customize the display hook, you need to create a new function that accepts a single argument, which is the value to be displayed. Here is an example of a custom display hook that appends a timestamp to the output:

import sys
import datetime

def custom_display_hook(value):
    timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
    print(f"{timestamp} {value}")

sys.displayhook = custom_display_hook

With the above code, every expression evaluated in the interactive console will be displayed with a timestamp prefix.

Restoring the Original Display Hook

If you want to revert back to the original display hook function, you can simply reassign the sys.__displayhook__ attribute:

import sys

sys.displayhook = sys.__displayhook__

This will restore the default behavior of printing the value to the console.

Conclusion

The sys.__displayhook__ attribute provides access to the original display hook function in Python. This allows you to customize the behavior of how results are displayed in the interactive console. By understanding this feature, you can enhance your experience when working in the Python interpreter.