barha barha - 1 month ago 5x
Python Question

Change decorator's parameter inside function

I am using flask-breadcrumbs add-on for python flask web server,
but I think this is more general question of python decorator,

@register_breadcrumb(app, '.', parameter)
def render_dashboard_page():

is it possible to set "parameter" from within the function "render_dashboard_page"?
I need parameter to be chosen based on "Accept-language" flag of the request, which I can determine only after the method was fired.

By the way, the 3rd input of "@register_breadcrumb" is the breadcrumb item title and I want it to be localized based on the "Accept-language" flag.

more information about the add-on:

Thanks :)


It's not possible to pass arguments to a function's decorator from inside the function, as the decorator executes before the function is defined. A guide on how decorators work can be found here and here - essentially, the decorator is a function that is passed the function below it, and then returns a function that should be inserted into the namespace.

Easier to give an example:

>>> def add_one(fn):
...     print("add_one called")
...     def wrap(n):
...         print("wrap called")
...         return fn(n) + 1
...     return wrap
>>> @add_one
... def times_by_two(n):
...     print("times_by_two called")
...     return n * 2
add_one called
>>> times_by_two(21)
wrap called
times_by_two called

I'm not entirely sure how that Flask plugin works, but you might be able to use the variable rules feature to do what you want. It looks like you can define a function to be called which returns text and a URL for the last component of the breadcrumbs, and the request object is accessible from that function; hopefully that's enough to be able to determine the user's language.