decorator

Use a class decorator to implement late-initialization

江枫思渺然 提交于 2020-01-03 16:17:07
问题 I am using some classes which need to connect to databases. The connection is only really needed when performing a real action. I want to delay the connection phase until it is really needed. For that, I want to do something similar to this: class MyClass def __init__(self): self.conn = None def connect(self): if self.conn : return self.conn = ConnectToDatabase() @connect def do_something1(self): self.conn.do_something1() @connect def do_something2(self): self.conn.do_something2() But I do

Python @precondition / @postcondition for member function - how?

丶灬走出姿态 提交于 2020-01-03 10:05:33
问题 I'm trying to use the @postcondition decorator on the value returned by a member function of a class, like this : def out_gt0(retval, inval): assert retval > 0, "Return value < 0" class foo(object): def __init__(self, w, h): self.width = w self.height = h @postcondition(out_gt0) def bar(self): return -1 When I try to call the member function 'bar' (and so provoke the @postcondition into providing a warning) I get this : >>> f = foo(2,3) >>> f.bar() Traceback (most recent call last): File "

Using Decorators in Python for Type Checking

江枫思渺然 提交于 2020-01-02 17:36:31
问题 This is more of a syntax error issue, I am trying to do this tutorial on Python Decorators http://www.learnpython.org/page/Decorators My Attempted Code def Type_Check(correct_type): def new_function(old_function): def another_newfunction(arg): if(isintance(arg, correct_type)): return old_function(arg) else: print "Bad Type" #put code here @Type_Check(int) def Times2(num): return num*2 print Times2(2) Times2('Not A Number') @Type_Check(str) def First_Letter(word): return word[0] print First

How to group decorators in Python

 ̄綄美尐妖づ 提交于 2020-01-02 04:48:28
问题 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

Flask hit decorator before before_request signal fires

▼魔方 西西 提交于 2020-01-02 02:01:18
问题 I'm using Flask and using the before_request decorator to send information about requests to an analytics system. I'm now trying to create a decorator that would prevent sending these events on a few routes. The problem I'm running into is getting my decorator to get called before the before_request signal gets fired. def exclude_from_analytics(func): @wraps(func) def wrapped(*args, **kwargs): print "Before decorated function" return func(*args, exclude_from_analytics=True, **kwargs) return

Decorator and closures

眉间皱痕 提交于 2020-01-01 22:15:51
问题 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

Why a recursion happens here?

假装没事ソ 提交于 2020-01-01 09:42:13
问题 Recently I read an interesting discussion on how to make a singleton in Python. One of the solutions was a tricky decorator defining a class inside its code as a substitute for decorated class: def singleton(class_): class class_w(class_): _instance = None def __new__(class2, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs):

Why a recursion happens here?

倾然丶 夕夏残阳落幕 提交于 2020-01-01 09:41:58
问题 Recently I read an interesting discussion on how to make a singleton in Python. One of the solutions was a tricky decorator defining a class inside its code as a substitute for decorated class: def singleton(class_): class class_w(class_): _instance = None def __new__(class2, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs):

Django Signal via Decorator on Model Method?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-01 09:22:52
问题 I'm trying to do something like these proposed signal decorators. In addition to having a decorator that connects the decorated method to a signal (with the signal's sender as an argument to the decorator), I would like to use the decorator on class methods. I'd like to use the decorator like so: class ModelA(Model): @connect.post_save(ModelB) @classmethod def observe_model_b_saved(cls, sender, instance, created, **kwargs): # do some stuff pass The decorator is: from django.db.models import

Does Python have decorators in the standard library?

余生长醉 提交于 2020-01-01 07:39:10
问题 Apart from @staticmethod and @classmethod ? Most languages have some basic libraries making use of most of the language features. It seems that many of the decorators I find myself making are things which tons of people would use, but I haven't found any inbuilt python decorators which do them. Are there such things? 回答1: property is usually used as a decorator. functools has several functions normally used as a decorator, such as total_ordering , update_wrapped , lru_cache , and wraps .