Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

3
  • 2
    I like this style the best, thanks for sharing. For others, I will note that if you try to mutate foo within wrapper, you may get an UnboundLocalError, in which case you should declare nonlocal foo (or perhaps choose a different local variable name, bar, and set bar = foo). See also: stackoverflow.com/a/57184656/1588795 Commented Aug 27, 2021 at 16:02
  • 1
    Note that this solution assumes that calling code always uses keyword arguments. In this case @decorator('foo') would not behave as expected. Commented Dec 3, 2021 at 12:22
  • 1
    @BjörnPollex Just change if func is None: to if not callable(func): if you want it to support positional arguments. Commented Oct 19, 2023 at 2:23