decorator

Decorating a class to monitor attribute changes

丶灬走出姿态 提交于 2019-12-18 13:48:30
问题 I want to have classes that automatically send notifications to subscribers whenever one of their attributes change. So if I would write this code: @ChangeMonitor class ChangingClass(object): def __init__(self, x): self.x = x changer = ChangingClass(5) print("Going to change x.") changer.x = 6 print("Going to not change x.") changer.x = 6 print("End of program") The output would be: Going to change x Old x = 5, new x = 6 Going to not change x. End of program. My question is how to implement

Python3 decorating conditionally?

狂风中的少年 提交于 2019-12-18 13:36:46
问题 Is it possible to decorate a function based on a condition? a'la: if she.weight() == duck.weight(): @burn def witch(): pass I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn ? If not, is it possible to create a condition within the decorator to the same effect? ( witch being called undecorated.) 回答1: You can create a 'conditionally' decorator: >>> def conditionally(dec, cond): def resdec(f): if not cond: return f return

Difference between Decorator pattern and Delegation pattern

懵懂的女人 提交于 2019-12-18 12:12:45
问题 What is the difference between Decorator pattern and Delegation pattern (if there is any) ? I don't want to know just about implementation details but also about use case differencies and subjective point of view how to use them. Decorator pattern Delegation pattern EDIT : Can you point to source code (in OS project) where these pattern (especially Delegation, because Decoration is used in Java IO classes) are used. I'm looking for some real usage not just dummy example. Maybe these patterns

Decorator pattern implementation

不羁岁月 提交于 2019-12-18 11:39:31
问题 Trying to implement the decorator pattern in C# from the code in the "Head First Design Patterns" book (written in Java). I am just starting out with C# and am therefore still new to the syntax, so I am not sure why I can't get the commented line of code below to work. Here is the first abstract-base class and its derived classes in the Decorator pattern: using System; public abstract class Beverage { private String m_description; // get a description of the beverage public virtual String

Java method missing (ala Ruby) for decorating?

给你一囗甜甜゛ 提交于 2019-12-18 10:46:09
问题 Is there any technique available in Java for intercepting messages (method calls) like the method_missing technique in Ruby? This would allow coding decorators and proxies very easily, like in Ruby: :Client p:Proxy im:Implementation ------- ---------- ----------------- p.foo() -------> method_missing() do_something im.foo() ------------------> do_foo p.bar() --------> method_missing() do_something_more im.bar() -------------------> do_bar (Note: Proxy only has one method: method_missing())

Determining if root logger is set to DEBUG level in Python?

泄露秘密 提交于 2019-12-18 10:44:12
问题 If I set the logging module to DEBUG with a command line parameter like this: if (opt["log"] == "debug"): logging.basicConfig(level=logging.DEBUG) How can I later tell if the logger was set to DEBUG? I'm writing a decorator that will time a function if True flag is passed to it, and if no flag is given, it defaults to printing timing information when the root logger is set to DEBUG. 回答1: logging.getLogger().getEffectiveLevel() logging.getLogger() without arguments gets the root level logger.

How to create abstract properties in python abstract classes

不问归期 提交于 2019-12-18 10:30:53
问题 In the following code, I create a base abstract class Base . I want all the classes that inherit from Base to provide the name property, so I made this property an @abstractmethod . Then I created a subclass of Base , called Base_1 , which is meant to supply some functionality, but still remain abstract. There is no name property in Base_1 , but nevertheless python instatinates an object of that class without an error. How does one create abstract properties? from abc import ABCMeta,

Flask: Decorator to verify JSON and JSON Schema

自古美人都是妖i 提交于 2019-12-18 10:26:28
问题 I have a flask application with calls expecting JSON payload. Before each call is processed, I have a 2-step error checking process: Assert that the payload is a valid JSON Assert that the JSON payload complies with a specific schema Which is implemented in the following fashion: @app.route('/activate', methods=['POST']) def activate(): request_id = request.__hash__() # Assert that the payload is a valid JSON try: input = request.json except BadRequest, e: msg = "payload must be a valid json"

Python 3 type hinting for decorator

我的梦境 提交于 2019-12-18 05:43:31
问题 Considere the following code: from typing import Callable, Any TFunc = Callable[..., Any] def get_authenticated_user(): return "John" def require_auth() -> Callable[TFunc, TFunc]: def decorator(func: TFunc) -> TFunc: def wrapper(*args, **kwargs) -> Any: user = get_authenticated_user() if user is None: raise Exception("Don't!") return func(*args, **kwargs) return wrapper return decorator @require_auth() def foo(a: int) -> bool: return bool(a % 2) foo(2) # Type check OK foo("no!") # Type check

Zend Framework 2 - Form Element Decorators

会有一股神秘感。 提交于 2019-12-17 22:37:08
问题 I want to force the Zend form into Twitter Bootstrap style. I currently iterate through the form fields and write the form info into my bootstrap div construction. I saw in Zend Framework 1(!) that there is a way to do this within a decorator. But for some reason the doc for version 2 doesn't cover this point... I'd like to do something like this: protected $_format = '<label for="%s">%s</label>' . '<input id="%s" name="%s" type="text" value="%s"/>'; public function render($content) {