Tránh dùng hàm lồng để làm giảm sự couple

Function Nesting Use Cases (mostly functional idioms, almost certainly incomplete since it’s off the top of my head):

  • closures
  • function factory (programmatic function creation based on parameters)
  • creating functions by calling functool.partial
  • creating functions by using lambda
  • any other reasons you need to create functions during call time

Trade-offs:

  • functions are strongly coupled
  • the code is always called (unless it’s in an if block)
  • additional code complexity
  • additional runtime cost (potentially, because the inner function get’s re-defined with every call to the outer function)
  • much harder to extend
  • much harder to introspect on the inner function defintion

Nguồn:: Stack Overflow, When to use python function nesting?


Cập nhật lần cuối : 2 tháng 2, 2024
Tạo : 12 tháng 10, 2023