python-decorators

Python decorator function called at compile time

旧城冷巷雨未停 提交于 2019-12-04 22:48:37
问题 I hope that someone familiar with Python's compilation / run-time procedures could shed some light on my question relating to how Python compiles decorator functions. Within my sample code, I've included a testing print statement in the "writeit" decorator just before the logtofile closure is defined. If you run the entire code that I've provided, the "testing" print statement in writeit is called for each @writeit decorator defined in the Customer class-- before writeit is ever used. Why is

Decorator and closures

╄→尐↘猪︶ㄣ 提交于 2019-12-04 21:50:11
I am going through the How to make a chain of function decorators? to understand decorator. In the following example, we see that "method_to_decorate" is accessible to wrapper function because of closures. But, I didn't understand how arguments self and lie are accessible to the wrapper function. def method_friendly_decorator(method_to_decorate): def wrapper(self, lie): lie = lie - 3 # very friendly, decrease age even more :-) return method_to_decorate(self, lie) return wrapper class Lucy(object): def __init__(self): self.age = 32 @method_friendly_decorator def sayYourAge(self, lie): print "I

Flask: why app.route() decorator, should always be the outermost?

有些话、适合烂在心里 提交于 2019-12-04 20:55:56
Say, I have a hand-crafted @login-required decorator: from functools import wraps def login_required(decorated_function): """Decorator to check if user is logged in.""" @wraps(decorated_function) def wrapper(*args, **kwargs): if False: # just to check it's working return decorated_function(*args, **kwargs) else: flash('You need to login, to access this page') return redirect(url_for('login')) return wrapper and a function, decorated with @app.route() and @login_required ( endpoint for login omitted for brevity ): @app.route('/') @login_required def index(): return "Hello!" Now, if I try to

Function decorators with parameters on a class based view in Django

送分小仙女□ 提交于 2019-12-04 16:49:21
问题 The official documentation explains how to decorate a class based view, however I could not find any information on how to provide parameters to the decorator. I would like to achieve something like class MyView(View): @method_decorator(mydecorator, some_parameters) def dispatch(self, *args, **kwargs): return super(MyView, self).dispatch(*args, **kwargs) which should be equivalent to @mydecorator(some_parameters) def my_view(request): .... How do I deal with such cases? 回答1: @method_decorator

What is the intended lifetime of a Python decorator?

两盒软妹~` 提交于 2019-12-04 14:52:50
My question revolves around the intended lifetime of an implemented Python decorator. From realpython.org it says: ''By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.'' To me, it seems like decorators quite frequently are used in examples online to temporarily modify or extend a python function, such as in the html formatting examples. Example : Let's say that I work at a web development company and at the top of all of my webpages I call this Python function page_welcome() . def page_welcome():

How do I use the python-decorator package to decorate classmethods?

梦想的初衷 提交于 2019-12-04 12:57:44
I'm have a decorator that I want to use to decorate class methods. In the following example, the @mydec decorator works fine on its own, however it does not preserve the function signature when using help() or pydoc. In order to fix this, I looked at using @decorator python-decorator package: import functools import decorator @decorator.decorator def mydec(func): @functools.wraps(func) def inner(cls, *args, **kwargs): # do some stuff return func(cls, *args, **kwargs) return inner class Foo(object): @classmethod @mydec def bar(cls, baz='test', qux=None): print (baz, qux) Foo.bar() Unfortunately

Pickling decorated callable class wrapper

有些话、适合烂在心里 提交于 2019-12-04 11:37:13
I'm struggling to pickle a wrapped function when I use a custom callable class as a wrapper. I have a callable class "Dependee" that keeps track of dependencies for a wrapped function with a member variable "depends_on". I'd like to use a decorator to wrap functions and also be able to pickle the resulting wrapped function. So I define my dependee class. Note the use of functools.update_wrapper. >>> class Dependee: ... ... def __init__(self, func, depends_on=None): ... self.func = func ... self.depends_on = depends_on or [] ... functools.update_wrapper(self, func) ... ... def __call__(self,

Python decorating class

断了今生、忘了曾经 提交于 2019-12-04 10:25:24
I'm trying to decorate a class with arguments but cannot get it to work: This is the decorator: def message(param1, param2): def get_message(func): func.__init__(param1,param2) return get_message class where I want to put the decorator @message(param1="testing1", param2="testing2") class SampleClass(object): def __init__(self): pass But this is not working , I am getting an error when running this. Does anyone know what the problem ?, I am trying to create a decorator to initialise classes with some values. I'm having trouble figuring out what you're trying to do. If you want to decorate a

Python decorator to keep signature and user defined attribute

本小妞迷上赌 提交于 2019-12-04 04:27:34
I have my simple decorator my_decorator which decorates the my_func . def my_decorator(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper._decorator_name_ = 'my_decorator' return wrapper @my_decorator def my_func(x): print('hello %s'%x) my_func._decorator_name_ 'my_decorator' Till here things work, but I can't see the actual signature of the function. my_func? Signature: my_func(*args, **kwargs) Docstring: <no docstring> File: ~/<ipython-input-2-e4c91999ef66> Type: function If I decorate my decorator with python's decorator.decorator , I can see the signature of my

Self-referencing inside class definition

喜欢而已 提交于 2019-12-04 03:26:19
问题 How do I reference class object inside class definition? Could you advice me how you would do it? Or more specifically how do you pass class object inside decorator of class method? Here is a simple example, I'm trying to pass second method I'm declaring to decorator of first one. def decorate(w): def _wrap(f): def _call(*args, **kwargs): return w(f(*args, **kwargs)) def _call return _wrap class A(): @dec(A.w) def f(): return 2 def w(f): return fr + 5 As expected exception is raised NameError