Menu
  • HOME
  • TAGS

Python - Count number of times function passes through decorator

python,decorator,python-decorators,functools

This should do it: from functools import wraps def count_check(function, count=[0]): """Returns number of times any function with this decorator is called """ @wraps(function) def increase_count(*args, **kwargs): count[0] += 1 return function(*args, **kwargs), count[0] return increase_count You could also get fancy and use a dictionary counting the functions individually as...

Detect if method is decorated before invoking it

python,decorator

You are using a double underscore name, which has undergone private name mangling in the run method. When stepping through the debugger, I get: AttributeError: "'function' object has no attribute '_MyFramework__skip_condition Don't use double underscore names here; if you rename the function attribute to _skip_condition the code works (provided you...

Python decorators calling functions in different classes

python,function,arguments,decorator

Decorators on methods are applied when the class is being defined, which means that the setup and teardown methods are not bound at that time. This just means you need to pass in the self argument manually. You'll also need to create an outer decorator factory; something that returns the...

Python Decorator with Arguments only called once

python,python-3.x,decorator,python-decorators

Move the check inside of the wrapped_f def __call__(self, f): def wrapped_f(*args, **kwargs): if not permitted: raise Exception("not authenticated to do that") f(*args, **kwargs) return wrapped_f Outside of the wrapped_f, it is checked at the creation of the function. Inside, it becomes part of the body of the new callable,...

How do I register decorators with AutoFixture?

c#,polymorphism,decorator,circular-dependency,autofixture

You need to freeze the IComponent first. Then, AutoFixture will re-use the same frozen IComponent instance when creating the LoggingDecorator class. Here are 2 ways of doing this: Using AutoFixture with Auto Mocking: PM> Install-Package AutoFixture.AutoMoq [Fact] public void UsingAutoFixtureAutoMoq() { var fixture = new Fixture() .Customize(new AutoMoqCustomization()); var expected...

Understanding my own decorator

python,unit-testing,tdd,decorator,httpretty

You are decorating methods, so your resulting wrapper function needs a self parameter, just like normal functions being used in a class. All that is different is that you used a different name fro that self parameter, test_case. As it happens, the instance is callable, and calling it runs the...

How do I use Decorator and Flyweight design patterns together?

design-patterns,design,decorator,flyweight

Design patterns are not "standards". Design patterns are common Appropriate [vs. Anti-patterns] solutions for common problems. And usually you don't build entire system by using certain design pattern. Rather your subsystems in your code are preferably done by some pattern. Even Asp.net MVC is not really a pattern - it...

Python-like C++ decorators

python,c++,function,macros,decorator

std::function provides most of the building blocks for my proposed solution. Here is my proposed solution. #include <iostream> #include <functional> //------------------------------- // BEGIN decorator implementation //------------------------------- template <class> struct Decorator; template <class R, class... Args> struct Decorator<R(Args ...)> { Decorator(std::function<R(Args ...)> f) : f_(f) {} R operator()(Args ... args) {...

Subclassing a decorated class

python,subclass,decorator,metaclass

You decorator is wrong. It should be returning a class instead of a function. def decorator_with_args(*args, **kwargs): def decorator(cls): class Wrapper(cls): def __init__(self, *wargs, **wkwargs): print(wargs, wkwargs) return Wrapper return decorator ...

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

python,django,decorator,python-decorators

Change: def __call__(self, function, *args): return "<p>{}</p>".format(self.tag, function(*args), self.tag) into: def __call__(self, function): def wrap(*args): return "<{}>{}</{}>".format(self.tag, function(*args), self.tag) return wrap You may want to look into functools for more refined decoration of wrap, but except for supporting help and the like, this should work....

code is cluttered by try-except in Python

python,exception,logging,decorator,contextmanager

You could put all your processes in a loop: allProcs = [process1, process2, processN] for path in paths: with open(path) as file: text=file.read() for proc in allProcs: try: proc(text) except Exception as e: # handle e record_failure( proc , file.name) continue ...

Javascript Decorator Pattern by Addy Osmani

javascript,prototype,decorator

extend( CaseDecorator, MacbookDecorator ); There is no inheritance taking place to the CaseDecorator from the MacbookDecorator, in fact, the prototype in that way is ignored completely and not beeing inherited by CaseDecorator. You're completely right about this. It looks like a lapse of the author to me, and should...

Python: Passing the default values of function' arguments to *args or **kwargs

python,python-3.x,decorator,default-value,metaclass

The wrapper is just a normal function. It does not have "access" to the internals of the wrapped function. You would have to use introspection to get them. See a related question: How to find out the default values of a particular function's argument in another function in Python?...

SimpleInjector decoration with additional dependency

c#,logging,dependency-injection,decorator,simple-injector

There are multiple ways to do this in Simple Injector. First of all, you can let your decorator's constructor depend on the DecoratorContext class. The DecoratorContext contains contextual information about the decorator. It contains information such as the types of the wrapped decorators and the type of the actual implementation...

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

python,decorator,mixins,python-decorators

In my opinion, you need mixins when you have a few different classes that should have same functionality. Good examples of using mixins are Django's class-based views. For example, you have a few different classes: FormView, TemplateView, ListView. All of them have one similar piece of functionality: they have to...

Passing different values to decorators for unit tests in Python

python,unit-testing,decorator,python-decorators

I assume you try to reduce the number of retrials to increase test speed. If so, modifying the number of retries variable doesn't seem to be the best approach. Instead, you could unit test the function mymethod without decorator first, and then create a mock function of mymethod. Let's call...

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

c#,dependency-injection,mono,decorator,autofac

You have this error because the C# compiler doesn't know which overload of the RegisterDecorator method to take. If you force it : builder.RegisterDecorator<ILastActivityUpdator>( new Func<IComponentContext, ILastActivityUpdator, ILastActivityUpdator>( (c, inner) => new AnonymousUserLastActivityUpdator(inner) ), fromKey: "lastActivityUpdator"); You will have a new error : AnonymousUserLastActivityUpdator does not contain a constructor that...

Domain error handler decorators in nodejs functions

jquery,node.js,error-handling,wrapper,decorator

An example: function sum(a, b) { return a + b; } function logDecorator(fn) { return function() { console.log(arguments); return fn.apply(this, arguments); }; } var sumLog = logDecorator(sum); sumLog(1, 10); // returns 11 and logs { '0': 1, '1': 10 } to the console sumLog(5, 4); // returns 9 and logs...

Changing values in decorator for nested functions

python,python-2.7,decorator,globals

I find it a little unclear as to what your goal is here. If you need to track per-function state, you can set a flag on the decorated function object itself: def decorator(*a): def real_decorator(function): def wrapper(*args, **kwargs): function.flag = False function(*args, **kwargs) function.flag = True return wrapper return real_decorator...

Dynamically override angular service?

angularjs,decorator,angular-decorator

Since decorating $http service would be the cleanest way of doing this, you can avoid polluting production code by using something like ng-constants and gulp/grunt to only add decoration code for a 'test' environment. See related Q/A here: angular js - configuration for different enviroments If you are inclined on...

Decorate general controller actions

php,design-patterns,decorator

You can use the built-in methods beforeAction (http://www.yiiframework.com/doc/api/1.1/CController#beforeAction-detail) and afterAction (http://www.yiiframework.com/doc/api/1.1/CController#afterAction-detail), inside your ControllerDecorator. This way you would be able to decorate every class tha extends ControllerDecorator. ps: I'm assuming you are using Yii. Right?...

Wrapping a function hides its attributes?

python,python-3.x,wrapper,decorator,wrap

functools.wraps() only copies across attributes. When you then increment the counter on the wrapped function, you are assigning a new integer value to the attribute, and the wrapper will still reference the old value. Instead of having wraps copy across attributes, have it copy across the whole __dict__ attribute of...

How can I decorate an instance of a callable class?

python,decorator

You question states: According to this popular answer, the @syntax is just sugar for: function = decorator(function) However, it's more accurate to say that @decorator def function(): pass Is syntactic sugar for: def function(): pass function = decorator(function) Decorators are designed to decorate function, method or class definitions, specifically. The...

Getting a decorator with args to work with method: self does not exist

python,oop,decorator

If you want to use an existing decorator function on an instance method, note that you can redefine instance methods in __init__, calling the decorator directly rather than using the @ syntax: class MyCls(object): def __init__(self): self.val = 1 self.onefrom1 = dodecorate(self.val)(self.onefrom1) def onefrom1(self, x): return x In use: >>>...

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

c#,decorator,ioc-container,structuremap

ObjectFactory is obsolete. You can exclude Decorator1<> from being registered as a vanilla ICommandHandler<> with code like this: var container = new Container(config => { config.Scan(scanner => { scanner.AssemblyContainingType(typeof(ICommandHandler<>)); scanner.Exclude(t => t == typeof(Decorator1<>)); scanner.ConnectImplementationsToTypesClosing(typeof(ICommandHandler<>)); }); config.For(typeof(ICommandHandler<>)).DecorateAllWith(typeof(Decorator1<>)); }); UPDATE For multiple modules...

Using pydispatch and decorators for class methods

python,decorator,class-method

You registered a function in a class. This means that just the function is registered, not a bound method. Functions are not bound to an instance, so no self argument is being passed in. You cannot hope to use the decorator on regular methods in a class definition, because the...

Using a decorated function as a function's default argument

python,python-2.7,logging,decorator,python-decorators

Note that the f(3) in def g(y=f(3)): is executed only once, when the function is defined, not every time when it is called. Thus, the problem seems to be that by the time f(3) is executed in mymodule, the logger is not yet initialized. Initialize first, then import, then it...

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

python,decorator

You were very close: class Master(SomeOtherClass): __flag = True class Child(Master): pass Two leading underscores without trailing underscores invokes name mangling, so the attribute will be named _Master__flag. Therefore if you check: hasattr(cls, '_{}__flag'.format(cls.__name__)) it will only be True for Master, not Child. ...

A decorator-creating class

python,class,decorator

You cannot have Decorator know what name it will be assigned to. Assignment occurs after instantiation, so the object will have already been created by the time it is assigned a name. You could however make a decorator that creates decorators dynamically: from functools import wraps def set_return_type(typeobj): def decorator(func):...

On multiple Class#extend calls

ruby,decorator,singleton-methods

extend adds to the list of ancestors, it doesn't replace any existing ancestors - if you examine coffee.singleton_class.ancestors after the second extend you can see that it includes both Milk and Sugar. If you are running 2.2, you can use the new super_method method to examine this: coffee.method(:cost) => #<Method:...

Local variable referenced before assignment in decorated method

python,python-3.x,decorator,python-decorators

You are assigning to method in the innermost function: message = message.format( name=self.name, cd=method_wrapper.cooldown.remaining, max_cd=method_wrapper.cooldown.limit ) That assignment makes it a local variable, but you cannot make that assignment without first accessing message. You cannot do that with a local. Since you don't want to modify the closed-over argument, you...

Validating the implementation of the Decorator Pattern in Java

java,design-patterns,decorator

The only improvement is to program against interfaces and not implementations. Use the Markable interface instead of SingleMarker in MarkerDecorator and MultipleMarker. It is also a question why MultipleMarker need to extend MarkerDecorator instead of directly implementing the interface. It your case it is not necessary. ...

python decorator proxy doesnt work

python,decorator

The problem here is that the self inside Foo.instance1 is a Foo instance, not a Decor instance. You can see this if you print out f.method1 itself: it's a bound method whose instance is f: >>> f.method1 attribute name of instance of class Foo = method1 <bound method Foo.method1 of...

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

python,class,decorator,with-statement

Each with statement creates a new instance of fcount2 so each instance only has one block_count - I don't have an answer but some additions to your code will illustrate what is happening. class fcount2(object): def __init__(self, inner_func): self.inner_func = inner_func self.count = 0 self.block_count =0 def __call__(self, *args, **kwargs):...

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

python,caching,decorator,nonetype

Possibly not the most perfect solution, but here's my go: import functools # http://stackoverflow.com/a/28961925/321973 def property_if_None_generator(f, cached=False): @functools.wraps(f) def wrapped(self): value = self.__getattribute__('_' + f.__name__) if value is not None: return value else: return f(self) if cached: wrapped = functools.lru_cache()(wrapped) return property(wrapped) property_if_None = lambda f: property_if_None_generator(f, cached=False) cached_property_if_None =...

Overriding the decorator of an abstract class in the inherited class

python,abstract-class,decorator

Decorators are applied to functions when the class is defined, their return values replace the functions they decorated. By the time the DataWrapper class has been defined, you can no longer alter what decorator is being used. Rather than use decorators, have the decorator delegate to another method on the...

Change an attribute of a function inside its own body?

python,function,python-3.x,decorator

Just set the attribute on wrapped_f instead of f. This requires you to set the initial count after defining the function, but that's no big deal: def keep_count(f): @functools.wraps(f) def wrapped_f(*args, **kwargs): f(*args, **kwargs) wrapped_f.count += 1 wrapped_f.count = 0 return wrapped_f Then with your decorated function: >>> test_f() ()...

Python write decorator for static method

python,regex,caching,decorator,static-methods

You need to follow this common pattern: you want a function which takes the intended parameters and returns a decorator function. def cachedAttributes(**kwargs): def decorator(func): func.__dict__.update(kwargs) return func return decorator Then: class someclass: @staticmethod @cachedAttributes(doctyperegex = re.compile(r'<!DOCTYPE.*?>\s*', re.S|re.U), htmlregex = re.compile(r'<html.*?>\s*', re.S|re.U), metaregex = re.compile(r'<meta(.*?)>', re.S|re.U)) def method(*args): # compile...

Python decorator with optional argument (which is function)

python,python-2.7,decorator,python-decorators

Since it is hard to tell decorator(func) from decorator(callback), make two decorators: from functools import wraps class MyCustomError(Exception): def __init__(self): print('in MyCustomError') # Common implementation def wrap(func,cb=None): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: if cb is not None: cb() raise MyCustomError() return wrapper # No parameters version...

Add a decorator to existing builtin class method in python

python,decorator,builtins

You cannot monkey-patch builtins, so subclassing is the only way (and actually better and cleaner IMHO). I'd go for something like this: class CustomList(list): def __init__(self, parent_instance, *args, **kwargs): super(CustomList, self).__init__(*args, **kwargs) self.parent_instance = parent_instance def append(self, item): self.parent_instance.added = True super(CustomList, self).append(item) class MyClass(object): added = False def __init__(self):...

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

python,inheritance,wrapper,decorator,super

OK. I solved it. Was a really simple mistake. In add_properties I returned the object of my class, but it needs to return the class itself. So my constructor was executed before my class was completely build. So I just changed it to the following and it works fine: def...

Python decorator TypeError 'object is not callable'

python,decorator,python-2.x

Your create_x function returns an integer: def create_x(): x = input('Give variable x a value: ') return x so create_x()() is never going to work. Part of the problem is that you've used poor parameter names, which is confusing you - you have two xs which refer to two completely...

C++ Decorator - Not working properly

c++,decorator

There are at least two serious errors. The first one is that you check definitions of manifest constants with suffix _H__ but define them without the suffix: #ifndef __TOWER_H__ #define __TOWER__ and #ifndef __TOWERDECORATOR_H__ #define __TOWERDECORATOR__ The second one is that you forgot to place a semicolon after class definition...

Why doesn't my idea work in python2?

python,python-3.x,decorator,python-2.x

The functools.wraps() version in Python 3 can handle function objects with some of the attributes it copies across missing; the one in Python 2 cannot. This is was because issue #3445 was fixed only for Python 3; the methods of dict are defined in C code and have no __module__...

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

java,design-patterns,override,decorator

Your abstract base type defines four abstract methods: public abstract int getCpu(); public abstract int getRam(); public abstract int getDisco(); public abstract String getCadena(); Your concrete derived type implements one of them: @Override public int getCpu() { return cpd.getCpu()+var; } The error is telling you that you have to implement...

working outside of aplication context in flask with a self made decorator

python,flask,decorator

Your decorator needs to provide a wrapper function, which will be called in place of the decorated function. Only when that wrapper is being called is an actual request being routed and can you test the session: from functools import wraps def requirir_login(func): @wraps(func) def wrapper(*args, **kwargs): if session['logged_in']: return...

How can i write python decorator for caching?

python,caching,decorator,python-decorators

You should remember that @decorator is just a syntactic sugar for func = decorator(func). So here comes a difference: (1) @decorator def func(): ... is same as func = decorator(func) # Just call of __init__ func(...) # Call of decorator.__call__ but (2) @decorator(some_param) def func(): ... is similiar to...

Decorator in python - explanation needed

python,decorator

Think of a decorator as a function that wraps your function. In math you might have a function f(x). If you wrap it with decorator g you have g(f(x)). In python the representation is @function_g def function_f(): pass Here's an example: def entryExit(f): def new_f(): print "Entering", f.__name__ f() print...

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

decorator,ecmascript-6,aurelia,aurelia-validation

The validation works in all kinds of situations, but using the @ensure decorator can only be used to declare your rules on simple properties (like you found out). Hence... Option a: replace the ensure decorator with the fluent API 'ensure' method, this supports 'nested' or 'complex' binding paths such as:...

How to decorate app methods in express?

javascript,node.js,express,decorator

Example of implementing your middleware: app.use(function(req, res, next) { if (req.path==='somePath' && req.headers.authorization ==='encoded user'){ //costum logic goes here next(); } else { res.sendStatus(403); } }); If you want to pass middleware only in one route you can implement like this: app.get(/*getPath*/, customFunc, function (req, res, next) { // regular...

issues with eclipse plugin decorator

xml,eclipse,plugins,decorator,readonly

You will have to write a decorator class (specify the class attribute) rather than using the icon attribute. The ILightweightLabelDecorator public void decorate(Object element, IDecoration decoration) method will be passed the IFile as the element so you can do your filtering on that. To deal with the file read only...

Simple Injector decorator for non-generic interface

decorator,simple-injector

Try this var container = new Container(); container.Register<IOp, SimpleOp>(); Container.RegisterDecorator(typeof(IOp), typeof(CompressOp)); var op = container.GetInstance<IOp>(); ...

Applying decorators to decorators

python,google-app-engine,python-2.7,flask,decorator

The easiest way to do this is to simply invoke the decorator you want to wrap on the wrapper you are returning: def registration_required(): @wraps(f) def decorated_function(*args, **kwargs): if(not is_registered_user(users.get_current_user().user_id())): return redirect(user_reg_url) return f(*args, **kwargs) return login_required(decorated_function) This works because the decorator syntax is just a shorthand: @decorator def some_func():...

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

python,decorator

In this case, name is going to be the argument passed to your function. In other cases, where we don't know much about the function, we can use *args and **kwargs where you have name in your decorator. A pretty concise explanation actually exists here.

Dynamically assigning sub class dependent decorators

python-3.x,dynamic,decorator

A decorated function or method is usually a different object than the function or method it decorates [*] - so, you can just wrap the original class' method in an explict way. This is rather straightforawrd, and rather boring - but it will work if you need to decorate just...

How to understand python decorator arguments pass

python,decorator

Not sure if i understand correctly your problem, but the default values for myfunc arguments are known only to myfunc - your decorator has no knowledge of them, so it cannot print them. That's why: myfunc() results in printing: () {} Both *args and **kw are empty for the decorator,...

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

c++,decorator

I see two solutions: 1 - Private inheritance struct A { void stuff() {} }; struct B : private A { using A::stuff; }; int main() { B b; b.stuff(); // OK } You'll need to list all of A's methods, but you don't have to redefine anything. 2 -...

Can decorators be a direct child of the component?

design-patterns,decorator

The main benefit you get with the Decorator Pattern is that, for client code, it's transparent. They don't need to know about the decorator, they can just treat it like a plain old concrete implementation of the base interface: ThingDoer thingDoer = new ThingDoerDecorator(new AwesomeThingDoer()); ThingDoer otherThingDoer = new AwesomeThingDoer();...

Django CBV with custom decorator

python,django,permissions,decorator

Apparently 1 of my views using kwargs['slug'] instead of self.kwargs['slug']. Funny that the only thing I've changed is adding that new mixin in my views. Wasted like 4 hours figuring this one out as it has been working fine for 1 month with just using kwargs['slug'].

Python decorator - func_wrapper() takes no arguments (1 given)

python,flask,decorator,restful-authentication

Consider using Flask-Login instead to handle authentication and redirect if the user is not logged in. (Or closely examine how it works.) It handles this much more robustly than the function you've written. The function you've written is not a decorator, and has many other issues. First, it needs to...

Draper with Bootstrap Pagination - undefined method 'total_pages'

ruby-on-rails,twitter-bootstrap,decorator,will-paginate,draper

https://github.com/drapergem/draper/issues/429 # app/decorators/application_decorator.rb class ApplicationDecorator < Draper::Decorator def self.collection_decorator_class PaginatingDecorator end end # app/decorators/paginating_decorator.rb class PaginatingDecorator < Draper::CollectionDecorator # support for will_paginate delegate :current_page, :total_entries, :total_pages, :per_page, :offset end # app/decorators/whatever_decorator.rb class WhateverDecorator < ApplicationDecorator end ...

How to register within a decorator all functions it decorates?

python,decorator,python-decorators

You can easily store a list on the decorator-function object (memoize.decorated): _decorated = [] def memoize(obj): cache = obj.cache = {} # add to the decorated list _decorated.append(obj) @functools.wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer # make the list accessible...

How to implement a parameter decorator in TypeScript?

annotations,typescript,decorator

The return value of this decorator is ignored. This is irrelevant to your situation. The return value of parameter decorators is ignored because they don't need to be able to replace anything (unlike method and class decorators which can replace the descriptor). My problem is that when I try...

Scoping problems with decorators in inheritance

python,inheritance,decorator

self.func() is a valiant attempt, but doesn't work because dot syntax will never care about a local named func. You want to make sure the function receives self, so just pass it in. return func(self, *args, **kwargs) ...

Decorator Pattern Confusion?

java,polymorphism,decorator

Yes exactly. If you depend on implementations not on abstractions(abstract classes or interfaces), that would be a serious problem for someone/you who wants to add a decorator in between. Please consult the Dependency inversion principle of Solid Principles. That's a general rule at it's core: one should “Depend upon Abstractions....

I need help following along this decorator. And confirmation if I'm correct

python,flask,decorator,wrap

f becomes index. This: @login_required def index(): return render_template('index.html', title='test home title') Is the same as this: def index(): return render_template('index.html', title='test home title') index = login_required(index) That is, the decorator is called with the decorated function as its argument....

Decorator flow and process

python,decorator,python-decorators

You are trying to 'decorate' the return value of the add() function call, not the add function itself. The proper equivalent would be to use: logger(add)(1, 2) so use the return value of logger() as the function to pass the 1, 2 arguments to. In other words, you need to...

Caching Decorator Python

python,caching,decorator

Yes, that's a mistake. If you're not sure, let's test it: def fib(n): if n < 2: return 1 return fib(n-2) + fib(n-1) print(fib(10)) @cache def cfib(n): if n < 2: return 1 return cfib(n-2) + cfib(n-1) print(cfib(10)) The first one prints out 89, the second one aborts: File "rhcache.py",...

Extending decorators

design-patterns,decorator

Intent of Decorator pattern: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. So the clients of the decorator or the undecorated target has a need to see both of them through the same contract. Hence, adding more methods to a...

Custom decorator is not allowing function to be called in main Python [duplicate]

python,decorator,python-decorators

Your decorator line creates an instance of your class: @ClassIBuilt('1', MessageConverter, timeout=10) That instance is then used to do the actual decorating; you in effect do this: decorator = ClassIBuilt('1', MessageConverter, timeout=10) def testfcn(): # ... testfcn = decorator(testfcn) Because decorator is an instance of your class, the decorator(testfcn) call...

Add a method to classes with a decorator

python,class,decorator

You need to do two things: Have myDecorator return the class object that it is passed: def myDecorator(cls): cls.dec_added_func = myFunction return cls Otherwise, the decorator will return None by default and you will get a TypeError whenever you do MyClass() for trying to call None. Make myFunction accept a...

How can I set module specific custom headers on a HTTP request?

angularjs,http,module,decorator,interceptor

Pretty sure this can't be solved just by separation using modules since as you've found the $http service is in the 'ng' module which is automatically included. When you inject $http you are getting the same instance that's defined in the 'ng' built-in module. Your best bet is probably to...

Extending the behavior of an inherited function in Python

python,function,inheritance,override,decorator

You mean something like this: class Base(object): def load(self): print('do logic A') print('do logic B') class Child(Base): def load(self): super().load() print('do logic C') c = Child() c.load() This will print: do logic A do logic B do logic C The only other way I can think of is this one:...

Python classes with decorated methods and __del__ defined do not get garbage collected: how do I uncouple the decorated method?

python,garbage-collection,decorator

It is not the decorator that causes this problem. It is the fact that you store a method on the instance they are bound to. The decorator is only the means here, not the actual cause. Methods hold a reference to the instance in __self__, and you then created a...

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

python,decorator

retry is a decorator that can either be used without arguments or with. If you give it arguments it'll act as a decorator factory and return the actual decorator. Call that returned decorator: a = retry(stop_max_attempt_number=3)(a) as that is the equivalent of using retry() as a decorator: @retry(stop_max_attempt_number=3) def a():...

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

python,decorator

One approach is to define and use a sentinel object to denote "call the same decorated function now executing. I.e, before the def try_except, add: same = object() and in the body of the wrapper, after the try/except: if on_exception is not None: if on_exception is same: return decorator(func)(*args, **kwargs)...

Decorate each item resolved in a collection with Castle Windsor

collections,castle-windsor,decorator

As it turns out, Castle.Windsor cannot do what I'm looking for out of the box. I tried looking into creating a new resolver to handle this scenario, but didn't get very far. In the end, I restructured to use a true factory to decorate the classes. class PrinterModifierFactory : IPrinterModifierFactory...

Pass a value from a decorator to a context processor in django

django,django-views,decorator

You can have the decorator add a property to the request object, and then access that value in the context processor. For example, you can use the following decorator: def add_value(function): def wrap(request, *args, **kwargs): request.extra_value = True return function(request, *args, **kwargs) return wrap Then you can access it in...

parse python functions as a string within decorator

python,decorator,python-decorators,python-magic

First of all, I suggest you do not do something like that. It's hard to get working code and very hard to make a correct version. Besides I don't really know what you want to do exactly. Should this decorator add a print statement after every assignment and show the...

AngularJS. Decorating model

javascript,json,angularjs,decorator

I have had this problem a number of times, and tried all of the solutions. In general, I will do the following: When it is something I may need to edit and send back, do not decorate, but instead use a separate list and lookup, like your #2 and #3....

Autofac constructor chaining

c#,inversion-of-control,decorator,autofac

There are several ways to build your container in order to achieve what you need, you can use keyed services or lambdas. Lambdas tend to be a bit less error prone than using strings , so here is a simple container registration that does what you need: ContainerBuilder cbLambdas =...

python wrapper function taking arguments inside decorator

python,decorator,python-decorators

What is the proper way to allow arguments in this simple wrapper? Thank you You need to pass the argument from my_function to wrapper, i.e.: def wrapper(x): If you want it to be able to handle many more functions generically then you'd have to do something like: def wrapper(*args,...

Patterns for decorating private methods of a class

c#,design-patterns,decorator

Use a list of IProcessor objects instead of a bunch of methods. Going this way you are able to add/skip/change call order. In your IProcessor declare Process(PerformanceContext context) method and implement PerformanceContext class to exchange some values like StartTime, NumberOfCalls etc. Good luck!...

Flow of python decorator functions

python,decorator

You called the decorator here: get_text = p_decorate(get_text) Normally, a decorator replaces a function with another callable (another function, for example), or returns the original function but having registered information about it. But by changing the return value of p_decorate() to "1" rather than the function wrapper, you 'broke' get_text...

How to skip a pytest using an external fixture?

python,decorator,py.test,python-decorators

It seems py.test doesn't use the test fixtures when evaluating the expression for skipif. By your example, test_ios is actually successful because it is comparing the function platform found in the module's namespace to the "ios" string, which evaluates to False hence the test is executed and succeeds. If pytest...

Rate-limiting python function decorator

python,algorithm,decorator,python-decorators,rate-limiting

You can use a threading.Semaphore to count and block the requests that are exceeding the limit, in combination with threading.Timer to schedule a function that releases the semaphore. from threading import Semaphore, Timer from functools import wraps def ratelimit(limit, every): def limitdecorator(fn): semaphore = Semaphore(limit) @wraps(fn) def wrapper(*args, **kwargs): semaphore.acquire()...

How to use decorator in observer pattern for Python 2.7

python,python-2.7,decorator

You cannot register bound methods until you have an instance for the method to be bound to. A function decorator alone does not have the context to detect when an instance has been created. You could use a metaclass / decorator combined approach instead: class ObservingMeta(type): def __call__(cls, *args, **kw):...

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

python,decorator

Use functools.wraps: from functools import wraps def decorate(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @decorate def test(a=1,b=2): return a+b print test.__name__ ...

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

python,methods,decorator

If your decorator can only work on methods (because you need access to the instance-specific lock) then just include self in the wrapper signature: from functools import wraps def decobj(func): @wraps(func) def wrapper(self, *args, **kwards): with self.lock: print 'Got the lock' func(self, *args, **kwards) return wrapper I included the @functools.wraps()...

Decorators - Throwing Invalid Syntax in Python

python,decorator

then you use the special keywoard "@func_name" in order to pass the next line of arguments into the function That's not how decorators work. You can pass arguments to a decorator like this @c("of python") def decorate_this_func(): pass But for that to work you need to tweak your decorator...

Error login_required django

django,decorator,login-control

I solved in a simple way, I do not know if it's the most efficient, but it worked. views def protected_message(request): return render(request, 'bands/protected_message.html') url url(r'^accounts/login/$', 'protected_message'), menu template <li><a href="{% url 'admin:index' %}">Login</a></li> protected_message.html {% extends "base.html" %} {% block title %} <title>Protected</title> {% endblock title %} {% block...

how to get request of flask in decorator logger?

python,flask,decorator

I think you can just add the following import from flask import request to customlog.py. Here's the test code I used that worked. I just replaced logging.debug with a simple print statement for testing. from functools import wraps from flask import request def webLog(func): @wraps(func) def newFunc(*args, **kwargs): print request.url...

About python class __init__ and Decorators

python,properties,decorator,init

For your first question , the answer is simple, x is an attribute of the class (not the object/instance of the class) , it would be evaluated when the class gets defined (not when its object is created). An Example to show this - >>> class CA: ... y =...

Decorator to invoke instance method

python,django,decorator

I think this does what you want: def validate_input(validation_fn_name): def validation_decorator(func): def validate_input_action(self, *args): error = getattr(self, validation_fn_name)(*args) if error is not None: raise error else: arglist = [self] + list(args) return func(*arglist) return validate_input_action return validation_decorator class Foo(object): def validate_length(self, arg1): if len(arg1) < 3: return ValueError('%r is too...

Why does the order of asynchronous and gen.coroutine matter in Tornado?

python,asynchronous,tornado,decorator,coroutine

Order matters because @asynchronous looks at the Future returned by @gen.coroutine, and calls finish for you when the coroutine returns. Since Tornado 3.1, the combination of @asynchronous and @gen.coroutine has been unnecessary and discouraged; in most cases you should use @gen.coroutine alone. However, the example you've shown here is kind...

Is there any pattern or practice to introduce debug/log code to an already existing algorithm in a non-intrusive way in .NET?

.net,algorithm,caching,logging,decorator

These look to me to be the classic types of cross cutting concerns that Aspect-Oriented programming is intended to address. Cross cutting concerns span layers and tiers in the code but ideally you want to implement in one place in a non-intrusive manner. Aspect Oriented programming allows behaviour to be...

How to automatically add and serialize virtual attribute to model object in rails module?

ruby-on-rails,ruby,design-patterns,module,decorator

I assume page_links would be a virtual attribute. Your code structure is complicated, and you can basically add page_links and page_links= methods to class Plugin with initialization, but if you want to keep this attribute in SomePluggin, you can do it in this way: module Cms class SomePluggin attr_accessor :page_links...

How to unit test open generic decorator chains in SimpleInjector 2.6.1+

c#,unit-testing,decorator,simple-injector,open-generics

The detail available for the dependency graph has been greatly improved in 2.6. You can achieve the same thing with this code: [Fact] public void RegistersIHandleQuery_UsingOpenGenerics_WithDecorationChain() { var container = this.ContainerFactory(); var instance = container .GetInstance<IHandleQuery<FakeQueryWithoutValidator, string>>(); var registration = ( from currentRegistration in container.GetCurrentRegistrations() where currentRegistration.ServiceType == typeof(IHandleQuery<FakeQueryWithoutValidator, string>)...

Apply a single decorator to multiple functions

python,decorator

If you want to make the "long" function call only once and decorate all three functions with the result, just do exactly that. my_patch = patch('somelongmodulename.somelongmodulefunction') @my_patch def test_a(patched): pass @my_patch def test_b(patched): pass ...