decorator

Using the decorator design pattern for a hierarchy of classes

徘徊边缘 提交于 2019-12-08 01:40:43
问题 Looking at the following (simplified) hierarchy of classes: > Email (base class) > SimpleEmail extends Email > HtmlEmail extends Email I need to decorate Email.send() to add throttling functionality. I need to instantiate SimpleEmail, HtmlEmail or other similar subclasses of Email. What should this pattern look like exactly? My guess (which surly needs correcting) is as follows: class abstract EmailDecorator -> Define a constructor: EmailDecorator(Email component) -> Implements all methods of

In Python, decorate two methods with the same name to distinguish them

心已入冬 提交于 2019-12-08 01:36:35
问题 I am writing a framework to be used by people who know some python. I have settled on some syntax, and it makes sense to me and them to use something like this, where Base is the Base class that implements the framework. class A(Base): @decorator1 @decorator2 @decorator3 def f(self): pass @decorator4 def f(self): pass @decorator5 def g(self) pass All my framework is implemented via Base's metaclass. This set up is appropriate for my use case because all these user-defined classes have a rich

Memoize a function so that it isn't reset when I rerun the file in Python

泄露秘密 提交于 2019-12-07 22:42:49
问题 I often do interactive work in Python that involves some expensive operations that I don't want to repeat often. I'm generally running whatever Python file I'm working on frequently. If I write: import functools32 @functools32.lru_cache() def square(x): print "Squaring", x return x*x I get this behavior: >>> square(10) Squaring 10 100 >>> square(10) 100 >>> runfile(...) >>> square(10) Squaring 10 100 That is, rerunning the file clears the cache. This works: try: safe_square except NameError:

Python: type checking decorator

眉间皱痕 提交于 2019-12-07 18:23:38
问题 I've built a type checking decorator (with wraps): def accepts_func(*types): """ top-level decoration, consumes parameters """ def decorator(func): """ actual decorator function, consumes the input function """ @wraps(func) def check_accepts(*args): """ actual wrapper which does some magic type-checking """ # check if length of args matches length of specified types assert len(args) == len(types), "{} arguments were passed to func '{}', but only {} " \ "types were passed to decorator '

how to pass in dynamic data to decorators

泪湿孤枕 提交于 2019-12-07 17:47:33
问题 I am trying to write a base crud controller class that does the following: class BaseCrudController: model = "" field_validation = {} template_dir = "" @expose(self.template_dir) def new(self, *args, **kwargs) .... @validate(self.field_validation, error_handler=new) @expose() def post(self, *args, **kwargs): ... My intent is to have my controllers extend this base class, set the model, field_validation, and template locations, and am ready to go. Unfortunately, decorators (to my understanding

Statement decorators

走远了吗. 提交于 2019-12-07 17:13:46
问题 We have some code that looks like this: from third_party_library import foo for n in range(3): try: foo(args) break except: print "Retry %i / 3" % n I would like to use a decorator, allowing our code to be more consise, looking like this: from third_party_library import foo @retry(3) foo(args) This gives a syntax error. Am I missing something, or does python just not allow decorators on statements? 回答1: Decorators can only be applied to function and class definitions such as: @decorator def

Decorators with arguments [duplicate]

拟墨画扇 提交于 2019-12-07 15:07:09
问题 This question already has answers here : Decorators with parameters? (10 answers) Closed 4 years ago . Code as follows def my_dec(func): def wrap(w): t = func(w) return t * 4 return wrap @my_dec def testing(n): return n new = testing(3) print(new) # This prints 12 This example is working fine, but now I'm trying to add the following to the decorator @my_dec(100) , I need to multiply the given number by 100. When I try this @my_dec(100) def testing(n): return n I get the following error:

Thymeleaf decorator is not working

╄→尐↘猪︶ㄣ 提交于 2019-12-07 13:15:33
问题 I created a new Spring-boot project and wanted to use Thymeleaf with the LayoutDialect. My pom.xml has following dependencies: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId>

Typescript decorators not working with arrow functions

感情迁移 提交于 2019-12-07 12:08:50
问题 I have a typescript decorator factory which console logs total time taken to execute a function, actual function execution results and parameters passed to the decorator as well. e.g. export function performaceLog(...args: any[]) { return (target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) => { var msg = ''; if (args.length != 0) { msg = args.map(arg => arg).join(' '); } if (descriptor === undefined) { descriptor = Object.getOwnPropertyDescriptor(target, key); } if (typeof

How do I infer the class to which a @staticmethod belongs?

落爺英雄遲暮 提交于 2019-12-07 12:06:37
问题 I am trying to implement infer_class function that, given a method, figures out the class to which the method belongs. So far I have something like this: import inspect def infer_class(f): if inspect.ismethod(f): return f.im_self if f.im_class == type else f.im_class # elif ... what about staticmethod-s? else: raise TypeError("Can't infer the class of %r" % f) It does not work for @staticmethod-s because I was not able to come up with a way to achieve this. Any suggestions? Here's infer_class