python-decorators

Does the order of decorators matter on a Flask view?

大兔子大兔子 提交于 2019-12-05 17:18:22
问题 I'm using the login_required decorator and another decorator which paginates output data. Is it important which one comes first? 回答1: While there probably won't be any problem in this case no matter what the order, you probably want login_required to execute first so that you don't make queries and paginate results that will just get thrown away. Decorators wrap the original function bottom to top, so when the function is called the wrapper added by each decorator executes top to bottom.

Flask decorator : Can't pass a parameter from URL

大兔子大兔子 提交于 2019-12-05 16:52:17
i'm quite new with flask and i'm trying to use the migthy power of decorators :p I read lot of things and found tons of topics about python decorators here but nothing really helpful. @app.route('groups/<id_group>') @group_required(id_group) @login_required def groups_groupIndex(id_group): #do some stuff return render_template('index_group.html') This is the error i get : @group_required(id_group), NameError: name 'id_group' is not defined Ok, id_group is not defined yet, but I don't understand why i CAN use the id_group parameter from the URL in the function groups_groupIndex but NOT in the

Modify function in decorator

三世轮回 提交于 2019-12-05 13:38:44
问题 I was thinking about making a decorator for the purpose of increasing performance. A decorator that modifies the source code of the function it decorates, and returns the modified function. While thinking this through, I figured that if I could just get the source code of the function, I could do this. But is it possible to access the source code of a function inside a decorator? If I have a decorator like this: import inspect def decorate(f): exec(inspect.getsource(f)) return eval(f.__name__

Python: Use of decorators v/s mixins? [closed]

倖福魔咒の 提交于 2019-12-05 11:45:51
问题 Closed . This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 4 years ago . I have understood the basics of decorators and mixins. Decorators add a new functionality to an object without changing other object instances of the same class, while a mixin is a kind of multiple inheritance used to inherit from multiple parent classes. Does it mean that

How to group decorators in Python

不羁的心 提交于 2019-12-05 11:13:24
In Flask I'm using a set of decorators for each route, but the code is "ugly": @app.route("/first") @auth.login_required @crossdomain(origin='*') @nocache def first_page: .... @app.route("/second") @auth.login_required @crossdomain(origin='*') @nocache def second_page: .... I would prefer to have a declaration that groups all of them with a single decorator: @nice_decorator("/first") def first_page: .... @nice_decorator("/second") def second_page: .... I tried to follow the answer at Can I combine two decorators into a single one in Python? but I cannot make it working: def composed(*decs):

Why does inspect return different line for class inheriting from superclass?

不羁的心 提交于 2019-12-05 09:37:07
While trying to figure out if a function is called with the @decorator syntax , we realized that inspect has a different behaviour when looking at a decorated class that inherits from a superclass. The following behaviour was found with CPython 3.6.2 under Windows 10. It was also reproduced in CPython 3.7.0 under Linux 64 bits. import inspect def decorate(f): lines = inspect.stack()[1].code_context print(f.__name__, lines) return f @decorate class Foo: pass @decorate class Bar(dict): pass Output Foo ['@decorate\n'] Bar ['class Bar(dict):\n'] Why does inheritance change the behaviour of inspect

Nesting descriptors/decorators in python

前提是你 提交于 2019-12-05 07:32:17
I'm having a hard time understanding what happens when I try to nest descriptors/decorators. I'm using python 2.7. For example, let's take the following simplified versions of property and classmethod : class MyProperty(object): def __init__(self, fget): self.fget = fget def __get__(self, obj, objtype=None): print 'IN MyProperty.__get__' return self.fget(obj) class MyClassMethod(object): def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): print 'IN MyClassMethod.__get__' def f(*args, **kwargs): return self.f(objtype, *args, **kwargs) return f Trying to nest them: class A

How to pass a class variable to a decorator inside class definition?

只愿长相守 提交于 2019-12-05 06:03:18
I'd like to use a decorator which accepts an argument, checks if that argument is not None, and if True it lets the decorated function run. I want to use this decorator inside a class definition, because I have a set of class methods which starts with checking if a specific class variable is None or not. I think it would look nicer if I used a decorator. I'd like to do something like this: # decorator def variable_tester(arg): def wrap(f): def wrapped_f(*args): if arg is not None: f(*args) else: pass return wrapped_f return wrap # class definition class my_class(object): def __init__(self):

How do I return a value when @click.option is used to pass a command line argument to a function?

白昼怎懂夜的黑 提交于 2019-12-05 05:24:02
I am trying to use click python package to pass a command line argument to a function. The example from official documentation works as explained. But nowhere in the documentation is it mentioned how to return a value back. None of the functions in the documentation returns a value, so I don't understand how to do this. Given example at documentation: import click @click.command() @click.option('--count', default=3, help='Number of greetings.') def hello(count): """Simple program that greets NAME for a total of COUNT times.""" for x in range(count): click.echo('Hello') if __name__ == '__main__

Wrapping all possible method calls of a class in a try/except block

点点圈 提交于 2019-12-05 04:33:16
问题 I'm trying to wrap all methods of an existing Class (not of my creation) into a try/except suite. It could be any Class, but I'll use the pandas.DataFrame class here as a practical example. So if the invoked method succeeds, we simply move on. But if it should generate an exception, it is appended to a list for later inspection/discovery (although the below example just issues a print statement for simplicity). (Note that the kinds of data-related exceptions that can occur when a method on