Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách định nghĩa hàm Python tại runtime

Dùng types.FunctionType và compile() để tạo function từ string code tại runtime.

Ví dụ

import types

code_str = 'print("Really Works")'
# compile(source, filename, mode)
code_obj = compile(code_str, 'dyn.py', 'exec')

# FunctionType(code, globals, name=None, argdefs=None, closure=None)
dynf = types.FunctionType(code_obj, {})

dynf()  # Really Works

Giải thích

  • compile(): Biên dịch source string thành code object. Mode: 'exec' (statements), 'eval' (expression), 'single' (single interactive statement).
  • types.FunctionType: Tạo function object từ code object + global namespace.
  • Namespace {} trống -> function không truy cập được biến ngoài trừ builtins.

Cách thực dụng hơn: exec()

namespace = {}
exec('def dynamic_func(x): return x * 2', namespace)
dynamic_func = namespace['dynamic_func']
print(dynamic_func(5))  # 10

⚠️ Cảnh bảo bảo mật

Không bao giờ exec/eval/compile code từ input người dùng không tin cậy (RCE vulnerability).