Python标准库是否存在调用被装饰函数的内置装饰器?
Great question! Let me start with a straight answer: Python's standard library does not include a dedicated decorator for this exact use case—even digging through functools, you won’t find a direct equivalent to your unclosure decorator.
Your implementation is clever and solves a handy, specific problem: it lets you define a closure-creating function, then automatically runs it to hand you the closure itself, instead of forcing you to call the factory function manually after defining it. For reference, here’s your code again:
def unclosure(f): return f() @unclosure def count(): x = 0 def _count(): nonlocal x x += 1 return x return _count assert count() == 1 assert count() == 2
Why isn’t this in the standard library?
The main reason is that this is a relatively niche pattern. Python’s standard library prioritizes general-purpose tools, and since this decorator is so trivial to implement (as you’ve shown), it’s left to users to build for their specific needs. Plus, it’s easy to extend the idea if you need to pass arguments to the closure-creating function—for example:
def unclosure(*args, **kwargs): def decorator(f): return f(*args, **kwargs) return decorator # Now you can pass parameters to your closure factory @unclosure(start=5) def make_counter(start): x = start def _count(): nonlocal x x += 1 return x return _count assert make_counter() == 6 assert make_counter() == 7
Checking other standard library modules
You mentioned checking functools, which is the right place to look for function-related utilities. None of the tools there match this use case:
functools.partialfixes arguments for a function, but doesn’t execute it to return a closure.functools.wrapspreserves metadata when decorating functions, which is unrelated here.functools.lru_cachecaches function results, but doesn’t handle closure creation in this way.
Final thought
Your implementation is totally valid and perfect for this scenario. Since it’s so lightweight and easy to tailor to your needs, there’s no real downside to keeping it as a custom utility in your codebase.
内容的提问来源于stack exchange,提问作者phsyron

