#๐ decorator wrapper function
28 messages ยท Page 1 of 1 (latest)
@lime dagger
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
because decorators return callables
we need to define the inner function so we have a callable to return
we don't usually care about the nested function outside the scope of the decorator function, so it makes sense to define it within
that is what the @decorator_function syntax would do
the latter snippet is not decorating anything
def decorator_function(func):
def wrapper():
print("I have decorated the function")
func()
return wrapper
def hello_world():
print("Hello world")
decorator_function(hello_world)
notice how we don't get Hello World printed here
!e
def decorator_function(func):
print("I have decorated the function")
func()
def hello_world():
print("Hello world")
decorator_function(hello_world)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | I have decorated the function
002 | Hello world
but we do here
This is a problem (and clearly different behaviour). We want the returned callable.
decorators let us modify how a function is called without changing the body of the actual function
if we think of functions as boxes that we open, a decorator is putting our box inside another box and then we open the outer box first before opening the inner box
this is useful if for example we wanted a decorator that makes a function requires a user to be logged in so they can perform an action
def require_login(f):
def wrapper():
if user_logged_in:
f()
else:
raise RuntimeError("User is not logged in")
@require_login
def check_inbox():
...
yes exactly
I work with 3d software and a common one I use is to treat a single function as one "undo chunk"
so I can group a bunch of actions together but if the user presses undo, it will go back to the start instead of undoing each individual action
def undo_chunk(f):
def wrapper():
cmds.undoInfo(openChunk=True)
f()
cmds.undoInfo(closeChunk=True)
@undo_chunk
def do_lots_of_stuff():
...
np!
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.