Python Byte-sized #3 – Function Introspection

CategorIes:

By

·

2–3 phút
  1. Giới thiệu
  2. Function Introspection dạng sơ khai
    1. dir() function
    2. Các function attributes phổ biến
  3. Package inspect
  4. Function Introspection trong code thực tế

Giới thiệu

Introspection là việc thực hiện kiểm tra và xem xét, đánh giá code mà ta đã viết bằng… code, hay nói cách khác ta thực hiện một cách programatically. Introspection có thể được thực hiện trên functions và objects, và trong bài viết này, ta sẽ tìm hiểu về function introspection.

Trong Python, function là một first-class object, hay nói cách khác, như một object thông thường, function cũng có các attributes (bao gồm propertiesmethods). Ví dụ, ta có thể dùng __doc__ property để lấy về docstring của function đó.

>>> sorted.__doc__
'Return a new list containing all items from the iterable in ascending order.\n\nA custom key function can be supplied to customize the sort order, and the\nreverse flag can be set to request the result in descending order.'

Hoặc, chúng ta cũng có thể set những properties mới lên một custom function:

>>> def my_func():
        print('inside func') 
>>> my_func.author = 'Hoang'
>>> print(my_func.author)
Hoang

Function Introspection dạng sơ khai

dir() function

dir() là một built-in function nhận vào một object và trả về list các attributes của nó. Ví dụ:

>>> dir(my_func)
['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__type_params__', 'author']

Các function attributes phổ biến

AttributeSử dụng
__name__Trả về tên của function/method
__defaults__, __kwdefaults__Trả về giá trị mặc định của positional arguments và keyword arguments
__code__Chứa thông tin về bytecode của hàm, số lượng tham số, và các local variables,…

Package inspect

Sử dụng các properties và functions built-in như trên sẽ khá bất tiện khi devs phải nhớ những edge cases và ý nghĩa của từng attributes. Package inspect sẽ giúp thực hiện introspection được dễ dàng hơn.

Package này cung cấp một vài functions hữu dụng như:

  • inspect.ismethod(obj): kiểm tra một object là một object method
  • inspect.isfunction(obj): kiểm tra một object là một function
  • inspect.getsource(my_func): truy xuất source code của function
  • inspect.getmodule(my_func): lấy về module mà ở đ my_func được định nghĩa
  • inspect.signature(my_func): trả về Signature instance, ta có thể sử dụng để check parameters,…

Function Introspection trong code thực tế

  • Ta có thể sử dụng inspect.getcomments để hiện thực một chức năng map từ TODO: sang vị trí của nó ở file nào/function nào, tương tự như trong một IDE.
  • Khi xây dựng tools cho LLM agents, ta có thể dùng inspect.signaturefunc.__name__ để tạo một prompt hướng dẫn LLM dùng tool, ở đó chứa các function name và signatures của chúng. Bạn có thể tham khảo code mẫu ở đây.

Cảm ơn mọi người đã đọc bài. Hẹn gặp bạn ở bài viết tiếp theo!

Bình luận về bài viết này