FAQ Database Discussion Community


Rate-limiting python function decorator

python,algorithm,decorator,python-decorators,rate-limiting
I found this rate-limiting python decorator based on redis classes. How can I write a similar decorator that uses only what's available in the standard library that can be used as follows? def ratelimit(limit, every): # 🐍 python magic 🐍 @ratelimit(limit=1, every=2) def printlimited(x): print x # print one number...

How to use @retry with keyword arguments AND pass a function

python,decorator
I am using the retrying (pip install retrying) package. I have a function like this - from retrying import retry from random import randint def a(): number = randint(0, 10) if number > 0: print number raise Exception("Some exception") else: return number # Case 1 a = retry(a) # This...

How can i write python decorator for caching?

python,caching,decorator,python-decorators
I'm trying to write python decorator for memoize. I have few questions. How does @memoize translate to memoize class's call function? Why does init expect an argument. Where is the cache stored? Is it associated with each and every function or it's a global variable? i.e Will there be two...

how should I user python decorator without changing the function name?

python,decorator
def decorate(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @decorate def test(a=1,b=2): return a+b print test.__name__ the result is wrapper. Is there any way make the result is "test"?...

How to implement a parameter decorator in TypeScript?

annotations,typescript,decorator
I've been trying to use a parameter decorator @logParameter: class Person { public name: string; public surname: string; constructor(name : string, surname : string) { this.name = name; this.surname = surname; } public saySomethingAsync(something: string, @logParameter cb: (said : string) => void) { cb(this.name + " " + this.surname +...

Domain error handler decorators in nodejs functions

jquery,node.js,error-handling,wrapper,decorator
I am trying to write a decorator for my node js function. Something like 'Test func a': custom_decorator( func(x)){ .. .. .. }) Let's say I want to add domain error handler to my function, I want to abstract domain error handling to all my functions.. var d = domain.create().on('error',...

DependencyResolutionException Circular component dependency detected: How to use Autofac to inject decorator?

c#,dependency-injection,mono,decorator,autofac
I have an interface called ILastActivityUpdator as follows: public interface ILastActivityUpdator { void UpdateLastActivity(int userId); } Besides that I have two classes that implement this interface, being LastActivityUpdator and a decorator AnonymousUserLastActivityUpdator. The latter one takes an ICookieProvider as extra argument and uses this in the method implementation. I.e., public...

How to decorate app methods in express?

javascript,node.js,express,decorator
I use node.js and express v4.12. I want to decorate all app.get calls by custom logic. app.get(/*getPath*/, function (req, res, next) { // regular logic }); and my custom logic customFunc() { if (getPath === 'somePath' && req.headers.authorization === 'encoded user'){ //costum logic goes here next(); } else { res.sendStatus(403);...

Passing different values to decorators for unit tests in Python

python,unit-testing,decorator,python-decorators
I have a situation where I'm trying to modify the arguments passed to a decorator on one of my class methods. The code looks something like this: class MyClass(object): @tryagain(retries=3) def mymethod(self, arg): ... do stuff ... My problem is I'd like to alter the "retries" variable to something less...

Python: How is the function argument treated inside a decorator?

python,decorator
I am trying to use decorators and find them kinda cool but I don't completely understand what is going on inside. Let's assume a simple example I borrowed from one of the pages about decorators. def p_decorate(func): def func_wrapper(name): return "<p>{0}</p>".format(func(name)) return func_wrapper def get_text(name): return "lorem ipsum, {0} dolor...

Python - Count number of times function passes through decorator

python,decorator,python-decorators,functools
I have a decorator that I wanna make increase a counter anytime a function is routed through the decorator. So far this is my code from functools import wraps def count_check(function): """Returns number of times any function with this decorator is called """ count = [] @wraps(function) def increase_count(*args, **kwargs):...

Python-like C++ decorators

python,c++,function,macros,decorator
Are there ways to decorate functions or methods in C++ like in python style? @decorator def decorated(self, *args, **kwargs): pass Using macros for example: DECORATE(decorator_method) int decorated(int a, float b = 0) { return 0; } or DECORATOR_MACRO void decorated(mytype& a, mytype2* b) { } Is it possible?...

SimpleInjector decoration with additional dependency

c#,logging,dependency-injection,decorator,simple-injector
I have a decorator SomethingLoggerDecorator that is supposed to decorate ISomething instances with logging: public class SomethingLoggerDecorator : ISomething { private readonly ISomething decoratee; private readonly ILogger logger; public SomethingLoggerDecorator(ISomething decoratee, ILogger logger) { this.decoratee = decoratee; this.logger = logger; } public void DoSomething() { this.logger.Info("Doing Something"); this.decoratee.DoSomething(); } public...

How to skip a pytest using an external fixture?

python,decorator,py.test,python-decorators
Background I am running a py.test with a fixture in a conftest file. You can see the code below(this all works fine): example_test.py import pytest @pytest.fixture def platform(): return "ios" @pytest.mark.skipif("platform == 'ios'") def test_ios(platform): if platform != 'ios': raise Exception('not ios') def test_android_external(platform_external): if platform_external != 'android': raise Exception('not...

how to use decorator pattern to directly modify members of base class?

c++,decorator
Base class A: class A { public: A() {} ~A() {} void methodOfA() { fill(array_.begin(), array_.end(), 100); } private: vector<int> array_; }; Decorator class B: class B: public A { A* a_; public: B(A* a) { a_ = a; } ~B() {} A* getA() { return a_; } }; Now...

Python: Use of decorators v/s mixins? [closed]

python,decorator,mixins,python-decorators
I have understood the basics of decorators and mixins. Decorators add a new functionality to an object without changing other object instances of the same class, while a mixin is a kind of multiple inheritance used to inherit from multiple parent classes. Does it mean that decorators should be used...

Define filter for DecorateAllWith() method in structure-map 3

c#,decorator,ioc-container,structuremap
I used following statement to decorate all my ICommandHandlers<> with Decorator1<>: ObjectFactory.Configure(x => { x.For(typeof(ICommandHandler<>)).DecorateAllWith(typeof(Decorator1<>)); }); But because Decorator1<> implements ICommandHandlers<>, the Decorator1<> class decorates itself too. So, the problem is that the Decorator1 registers inadvertently, when I register all the ICommandHandler<>'s. How can I filter DecorateWithAll()to decorate all ICommandHandler<>,...

A decorator-creating class

python,class,decorator
I am writing a bunch of code that has a possibility of mutable outputs, like an arithmetic function where I could have the output be a float or an int. Basically my problem is that if I were to create a decorator for each object type I need (probably seven...

Detect if method is decorated before invoking it

python,decorator
I wrote a Python flow control framework that works very similarly to unittest.TestCase: the user creates a class derived from the framework class, and then writes custom task_*(self) methods. The framework discovers them and runs them: ################### # FRAMEWORK LIBRARY ################### import functools class SkipTask(BaseException): pass def skip_if(condition): def decorator(task):...

Autofac constructor chaining

c#,inversion-of-control,decorator,autofac
How would I implement the equivalent using Autofac to output 123. I've had a look at the following but I don't think it quite fits in with what I'm trying to achieve. http://docs.autofac.org/en/latest/advanced/adapters-decorators.html Maybe someone can enlighten me - is this decorator? using System; namespace Prototypes.Decorator { public class Program...

Django CBV with custom decorator

python,django,permissions,decorator
I'm trying to create a custom access permission base on where does my staff work. For example if they're working at clinic A, they can only view/add/modify data for that clinic A. But if they're incharge of that district, they can access all those clinic in that district. It work...

How to register within a decorator all functions it decorates?

python,decorator,python-decorators
Say you have the following decorator. How can it be modified to say append to some list references to all the functions it decorates? def memoize(obj): cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer @memoize def...

python wrapper function taking arguments inside decorator

python,decorator,python-decorators
I am trying to write python decorators and I am having problems understanding how the internal wrapper takes arguments. I have here: import time def timing_function(some_function): def wrapper(): t1 = time.time() some_function() t2 = time.time() return "Time it took to run: " + str((t2-t1)) + "\n" return wrapper @timing_function def...

Changing values in decorator for nested functions

python,python-2.7,decorator,globals
I have a case similar to this - flag = True print "Before All things happened, flag is", flag def decorator(*a): def real_decorator(function): def wrapper(*args, **kwargs): global flag flag = False print "just in real decorator before function call i.e. before", function.__name__ print "flag is " , flag function(*args, **kwargs)...

Python decorator TypeError 'object is not callable'

python,decorator,python-2.x
I am trying to get myself familiar with decorators. This is a program I created to do so, but it keeps giving me an TypeError: 'int' object is not callable error, which I don't know how to fix. #Filename: decorator_practice.py def add(x): def add_1(): add_1 = x() + 1 return...

Apply a single decorator to multiple functions

python,decorator
I've searched for this, but the results I've seen involve the opposite: applying multiple decorators to a single function. I'd like to simplify this pattern. Is there a way to apply this single decorator to multiple functions? If not, how can I rewrite the above to be less repetitious? from...

“is not abstract and does not override abstract method java” using Decorator Pattern

java,design-patterns,override,decorator
public abstract class AdicionalesCpd extends Cpd{ public abstract int getCpu(); public abstract int getRam(); public abstract int getDisco(); public abstract String getCadena();} This my abstract class for the decorator pattern, and I have this problem when it compiles: **error: Cpu is not abstract and does not override abstract method getCadena()...

Simple Injector decorator for non-generic interface

decorator,simple-injector
I tried the following but doesn't work (ActivationException). public interface IOp { object Execute(object value); } public class SimpleOp : IOp { public object Execute(object value) { return value; } } public class CompressOp : IOp { private readonly IOp nextOp; public CompressOp(IOp nextOp) { this.nextOp = nextOp; } public...

issues with eclipse plugin decorator

xml,eclipse,plugins,decorator,readonly
I'm adjusting my current eclipse plugin for some gimmicks and made my own decorator for files and folders. the current file decorator looks like this: <decorator lightweight="true" id="com.tdm.eclipse.plugin.decorators.readonly" label="readOnly file decorator" icon="icons/readonly.ico" state="true" location="TOP_LEFT" adaptable="true"> <description> readOnly file decorator </description> <enablement> <and> <objectClass name="org.eclipse.core.resources.IFile"/> <objectState name ="readOnly"...

How to add attribute to python *class* that is _not_ inherited?

python,decorator
I need to be able to set a flag on a class (not on an instance of a class) which is not visible to a subclass. The question is, is it possible, and how would I do it if it is? To illustrate, I want something like this: class Master(SomeOtherClass):...

Decorators - Throwing Invalid Syntax in Python

python,decorator
This may be an OS problem since I did saw on youtube videos where people were demoing how to use decorators in python in a Linux based system. So I'm trying to play with decorators. In its usual form, you create a function of it first, and then you use...

Dynamically assigning sub class dependent decorators

python-3.x,dynamic,decorator
I have a class that has a basic method, and subclasses that have the same base functionality, but additional behaviour, which can be implemented with decorators. class cls_with_basic_method: #if...exec("@decoratorA") #if...exec("@decoratorB") #... def basic_method(arg): #... return arg class cls_with_basic_method_and_decoratorA(class_with_basic_method): #... class cls_with_basic_method_and_decoratorB(class_with_basic_method): #... #... It seems the quickest solution would be...

How can i write a decorator using a class's __call__ function?

python,django,decorator,python-decorators
The following is my code. Given any content, it has to append certain HTML tag to the content at the front. I'm learning to write decorators using call instead of function closures. class decorate: def __init__(self, tag=""): self.tag = tag def __call__(self, function, *args): return "<p>{}</p>".format(self.tag, function(*args), self.tag) @decorate(tag="p") def...

How to use aurelia-validate with a object properties to validate?

decorator,ecmascript-6,aurelia,aurelia-validation
I'm using aurelia-validate and my validation works fine if I use variables, but I need it to validate properties of an object rather than a variable: Here's what works: import {Validation} from 'aurelia-validation'; import {ensure} from 'aurelia-validation'; import {ItemService} from './service'; export class EditItem { static inject() { return [Validation,...

Draper with Bootstrap Pagination - undefined method 'total_pages'

ruby-on-rails,twitter-bootstrap,decorator,will-paginate,draper
I'm using Draper to decorate my views and move some logic out of them but I'm struggling with this question - how to setup Draper with Bootstrap Pagination (will_paginate)? By default I have this: delegate_all And from Draper documentation I've tried adding this: delegate :current_page, :per_page, :offset, :total_entries, :total_pages But...

Patterns for decorating private methods of a class

c#,design-patterns,decorator
In the below class I have a public method called ProcessMessage. This method is responsible for processing the incoming messages. Processing a message involves different stage. I want to decorate this class in such a way that I can publish performance counter values from each stage of the message processing....

Decorator Pattern Confusion?

java,polymorphism,decorator
I've been doing some research on the decorator pattern, and there is a bit of confusion with understanding one of it's problems. I keep reading that "decorators are typically transparent to the client of the component; that is, unless the client is relying on the component's concrete type". I'm not...

What is the best way to decorate methods of a Python class?

python,methods,decorator
I am following below conventions to decorate certain methods in a Python class. I am wondering if there are some better ways to do the same. My approach certainly doesn't look good; the call to original member function doesn't look intuitive at all. from threading import Lock def decobj(fun): def...

Local variable referenced before assignment in decorated method

python,python-3.x,decorator,python-decorators
I'm creating a decorator that would allow me to do stuff like: @cooldownf(lambda self, **eargs: 30 - self.level) def method(self, **eargs): ... Which would simply decorate the method so that it has a cooldown. This all worked just fine and the method can now be executed every 30 - self.level...

Javascript Decorator Pattern by Addy Osmani

javascript,prototype,decorator
Given this code: // Constructor. var Interface = function (name, methods) { if (arguments.length != 2) { throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2."); } this.name = name; this.methods = []; for (var i = 0, len = methods.length; i < len;...

In a decorator how can I pass the function I'm decorating as an argument?

python,decorator
I made this simple decorator which basically puts the decorated function in a try...except. from functools import wraps def try_except(on_exception=None, exception=Exception, *args, **kwargs): from sys import stderr def decorator(func): @wraps(func) def wrapper(*args1, **kwargs1): try: return func(*args1, **kwargs1) except exception as e: print(repr(e), file=stderr) if on_exception is not None: return on_exception(*args,...

Extending the behavior of an inherited function in Python

python,function,inheritance,override,decorator
Let's say we have the following classes: class Base(object): def load(self): # do logic A # do logic B class Child(Base): def load(self): # do logic C I know decorators can be used to extend function behavior in Python but I don't know how I can apply it in my...

Using pydispatch and decorators for class methods

python,decorator,class-method
I am trying something fairly simple. I want to write a decorator which turns a class method in an event handler using pydispatcher. Here is my down-to-the-essentials approach: from pydispatch.dispatcher import connect,send,Any SIGNAL = "test" def triggered(func): connect(func,signal=SIGNAL,sender = Any) return func class P(object): @triggered def a(self,*args,**kwargs): print "yay" if...

Caching Decorator Python

python,caching,decorator
I was watching one of Raymond Hettinger's awesome videos and I got a bit confused on the decorator example: def cache(func): saved={} @wraps(func) def newfunc(*args): if args in saved: return newfunc(*args) # should be return saved[args]? result = func(*args) saved[args]=result return result return newfunc I'm not particularly an expert on...

parse python functions as a string within decorator

python,decorator,python-decorators,python-magic
I am trying to write a function debug decorator that will look at: def foo(baz): bar = 1 bar = 2 return bar and wrap it to: def foo(baz): bar = 1 print 'bar: {}'.format(bar) bar = 2 print 'bar: {}'.format(bar) return bar I need to play with the function...

Python Decorator Class: How to correctly count function calls in a with block

python,class,decorator,with-statement
I am writing a simple decorator class in python that counts function calls. So far my code is able to count function calls correctly, even in a with block. My issue is that I also want to keep track of how many times I call decorated functions inside of a...

How to have a decorator return a (cached) property iff it was previously None?

python,caching,decorator,nonetype
In a class where an argument is optional and calculated else, I typically have something like class Demo(object): def __init__(self, value=None): self._value = value @property def value(self): if self._value is None: # some calculations to get value self._value = value return self._value which is quite noisy IMHO and similar to...

Python: How to call super when the class itself has a decorator?

python,inheritance,wrapper,decorator,super
I need to call the inherited class to get it's content and methods to work. But I also have a class decorator assigned to my wrapper classes. I have a lot of wrapper classes and want them to be as short as possible, that's why I try to get this...

Validating the implementation of the Decorator Pattern in Java

java,design-patterns,decorator
I am learning hands on implementation of Design Patterns. The following is an implementation of the Decorator Design Pattern. I would like to know if the implementation is correct. Let me know if it can be improved or is incorrect. interface Markable { void mark(); } class SingleMarker implements Markable...

Decorate each item resolved in a collection with Castle Windsor

collections,castle-windsor,decorator
Suppose I have an interface with multiple base implementations: interface IPrinter { void Print(); } class Printer1 : IPrinter { public void Print() { Console.WriteLine(GetType()); } } class Printer2 : IPrinter { public void Print() { Console.WriteLine(GetType()); } } I also have a decorator implementation: class ModifyingPrinter : IPrinter {...