python-decorators

How can I make class properties immutable?

 ̄綄美尐妖づ 提交于 2021-02-19 06:52:06
问题 @property is a nice way to define getters. When the property is mutable, the reference returned can be used to modify the property in ways not controlled by the class definition. I'll use a banana stand as a motivating analogy, but this issue applies to any class that wraps a container. class BananaStand: def __init__(self): self._money = 0 self._bananas = ['b1', 'b2'] @property def bananas(self): return self._bananas def buy_bananas(self, money): change = money basket = [] while change >= 1

How to apply a decorator to all views (of a module) in django

点点圈 提交于 2021-02-18 22:21:13
问题 It happens a lot, when all the views in a specific module are supposed to be available only when the user is authorized, or they should all do the same checks. How could I avoid repeating the annotations all over the file? 回答1: When using class-based views you can create a base class/mixin for all these views which implements the desired functionality (also using decorators) and then have all the views inherit from this base view. from django.views.generic import TemplateView class BaseView

Django - how to tell if user was redirected to the page by @login_required?

僤鯓⒐⒋嵵緔 提交于 2021-02-11 14:20:16
问题 I want to use the @login_required decorator for a view called allUsers_page , which is used when you go to the url r'^users/allUsers$' In my settings.py, I have LOGIN_URL='/login' so when a user goes to the allUser_page view (when he goes to the url users/allUsers , if the user is not signed into his account, it will redirect him to the login page. Now, in the login page, is there a way for me to find out if the user just went to the login page directly or if he was redirected to the login

Why does python class method’s first argument change when used as decorator

笑着哭i 提交于 2021-02-11 05:59:20
问题 Consider the following code: class C: def decorator(self): print(self) def inner(*args): return self(*args) return inner @decorator def decorated(self): ... if __name__ == '__main__': c = C() c.decorator() # 1 c.decorated() #2 The output is this: <function C.decorated at 0x1121cd9d8> <__main__.C object at 0x111f5a8d0> When the decorator function is called as a normal class function, the first argument it receives is a class instance. However, when decorated is called and the decorator

Why does python class method’s first argument change when used as decorator

♀尐吖头ヾ 提交于 2021-02-11 05:57:25
问题 Consider the following code: class C: def decorator(self): print(self) def inner(*args): return self(*args) return inner @decorator def decorated(self): ... if __name__ == '__main__': c = C() c.decorator() # 1 c.decorated() #2 The output is this: <function C.decorated at 0x1121cd9d8> <__main__.C object at 0x111f5a8d0> When the decorator function is called as a normal class function, the first argument it receives is a class instance. However, when decorated is called and the decorator

Decorating a decorator

夙愿已清 提交于 2021-02-10 05:40:55
问题 I tried to do some argument modification on a decorator which decorates a function. The original code looks like @original_decorator(arg=some_object) def calculate(a, b): # complex business logic raise Exception() where original_decorator is responsible for exception handling. What I want to achieve is to do some temporary modification on some_object and restore it's property after function returned. And I've tried the following def replace_arg(arg, add_some_property): def decorator_wrapper

How to add a custom decorator to a FastAPI route?

拈花ヽ惹草 提交于 2021-02-10 05:21:26
问题 I want to add an auth_required decorator to my endpoints. ( Please consider that this question is about decorators, not middleware ) So a simple decorator looks like this: def auth_required(func): def wrapper(*args, **kwargs): if user_ctx.get() is None: raise HTTPException(...) return func(*args, **kwargs) return wrapper So there are 2 usages: @auth_required @router.post(...) or @router.post(...) @auth_required The first way doesn't work because router.post creates a router that saved into

Memoizing decorator keeping stored values

烈酒焚心 提交于 2021-02-07 04:21:13
问题 I have a memoization decorator that looks like this: def memoize(obj): from functools import wraps cache = {} @wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer However, I'm not sure this function works properly because it seems like to me it recreates cache as an empty dictionary every time the decorated function is called. When I test it with a simple fibonacci function, it does appear to memoize correctly.

Memoizing decorator keeping stored values

孤者浪人 提交于 2021-02-07 04:21:05
问题 I have a memoization decorator that looks like this: def memoize(obj): from functools import wraps cache = {} @wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer However, I'm not sure this function works properly because it seems like to me it recreates cache as an empty dictionary every time the decorated function is called. When I test it with a simple fibonacci function, it does appear to memoize correctly.

Doctest and Decorators in Python

青春壹個敷衍的年華 提交于 2021-02-07 03:54:47
问题 I was trying to use Python decorator to catch exceptions and log the exceptions. import os.path import shutil class log(object): def __init__(self, f): print "Inside __init__()" self.f = f def __call__(self, *args): print "Inside __call__()" try: self.f(*args) except Exception: print "Sorry" @log def testit(a, b, c): print a,b,c raise RuntimeError() if __name__ == "__main__": testit(1,2,3) It works fine Desktop> python deco.py Inside __init__() Inside __call__() 1 2 3 Sorry The issue is that