RSS Amplifier

A sonic soul with a relentless drive to make ideas real on JmsDnns · Aug 21, 2023

Decorators 101

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

It is underappreciated that Python decorators are syntactic sugar for function wrappers. People new to Python usually encounter them first by writing like @foo above a function bar and observing that bar behaves differently than it used to. More tangibly, using the @foo decorator on bar looks like this. @foo def bar (): print ( 'hello!' ) To understand decorators is to understand function…

It is underappreciated that Python decorators are syntactic sugar for function wrappers. People new to Python usually encounter them first by writing like @foo above a function bar and observing that bar behaves differently than it used to.

More tangibly, using the @foo decorator on bar looks like this.

@foo
def bar():
 print("hello!")

To understand decorators is to understand function wrappers, but understanding those requires being comfortable with first class objects, so we’ll start there. We will then explain function wrappers, using an example time_it that determines how long it takes for a function to complete. We then use decorator syntax to apply our wrapper in a clean, elegant way.

Read on /tech/decorators/

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.