Working through the django tutorials and came across the following code:
@admin.display(
boolean=True,
ordering='pub_date',
description='Published recently?',
)
Had no idea what it was so I did some googling and learned what decorators are in Python. I feel comfortable with that topic.
However, in all the videos and docs I went through I didn't see an example like @admin.display()
Only things like @log
or @timer
. Pretty much just a simple class or function decorator.
My guess is that @admin.display
is a decorator where admin
is the class and display
is one of many wrapper methods(is that even possible) in that class?
Just confused I guess as to the syntax as I can't find any examples like it :(
CodePudding user response:
The way to parse this is:
@
is special decorator syntaxadmin
and its attributedisplay
are both objects- the
(boolean=True, ...)
meansdisplay
must be callable, i.e.display.__call__()
will be executed
When you see something like:
@log
def my_method():
return 'blah'
It's effectively the same as: my_method = log(my_method)
Next, consider:
@configurable_log(config_val)
def my_method():
return 'blah'
Which is the same as: my_method = configurable_log(config_val)(my_method)
configurable_log
is a callable taking config args (i.e. configurable_log(config_val)
) which returns another callable, which is passed my_method
. In other words, it's the same as:
configured_log_decor = configurable_log(config_val)
@configured_log_decor # a "no parens" decorator
def my_method():
return 'blah'
The last remaining part is just normal attribute access, e.g.:
SomeClass.attr_of_class
some_instance.attr_of_instance
some_module.attr_of_module