Questions tagged [decorator]
Decorator is an object-oriented design pattern that allows adding behavior to existing classes in a dynamic fashion. It is one of the Gang of Four's structural design patterns.
4,583
questions
1
vote
1
answer
31
views
How to pass a value from controllers to service methods with decorator in nestjs?
I have a controller as follows:
@Controller()
class UserController {
@Post("/order")
@ApiBearerAuth()
async createOrder(@Body() order: Order, @GetHeaderItem("HEADER-ITEM") ...
0
votes
0
answers
34
views
Is this Class-Structure a Decorator Pattern? [closed]
Is this classstructure a decorator, or how would you describe it? \ I have tried to Implement this Pattern as shown in the picture. My Code works perfectly fine, but i want to understand structural ...
0
votes
1
answer
25
views
Python context-manager decorator masks my exception?
Following the examples in https://docs.python.org/3/library/contextlib.html ..
In the synthetic code below:
import sys
from contextlib import contextmanager, nullcontext
class MyException(Exception):
...
0
votes
1
answer
22
views
Decorator won't work: 'NoneType' object is not callable
import numpy as np
def multi_print(n):
def decorator(func):
def wrapper(*args, **kwargs):
for z in np.arange(n):
print(func(*args))
@multi_print(2)
def ...
-1
votes
0
answers
24
views
Is there a way to "update" python function returns after a specified amount of time?
I have a function timeslots() in a flask app which returns the events from a Google Calendar using their service account API.
@app.route('/timeslots', methods=['GET'])
def timeslots():
events = ...
1
vote
1
answer
36
views
Create decorator for recursion count
I need to create a decorator to call Ackermann function and write down its attributes: the number of recursions and execution time.
I tried the below code but it works wrong.
Could anyone help?
def ...
1
vote
1
answer
15
views
module not found error whle using librosa keyword
Exception has occurred: ModuleNotFoundError
No module named 'numba.decorators'
File "C:\Users\prasa\OneDrive\Desktop\Python\Untitled-1.py", line 3, in
import librosa
0
votes
1
answer
23
views
Nestjs custom class-validator decorator doesn't get the value from param
I have created a Custom ValidatorConstraint in Nestjs from class-validator, just to create my own decorator and apply later to DTO classes for validations.
Imagine this route.
foo/:client
after ...
0
votes
0
answers
15
views
ignore method decorator inside test _ Javascript
suppose we have class A with a method called foo inside it. and we have a decorator function that is responsible for decorating method foo.
class A {
@decorate_foo
foo() {
}
}
...
0
votes
0
answers
23
views
what are the steps javascript engine take when it encounters a wrapper function
I came across this code while trying to understand how the JavaScript engine interprets wrapper functions. I want to know what are the steps the engine takes when it executes wrapper function code and ...
5
votes
1
answer
60
views
Controlling context manager in a meta class
I would like to know if it's possible to control the context automatically in a metaclass and decorator. I have written a decorator function that creates the stub from the grpc insecure channel:
def ...
0
votes
1
answer
61
views
In python, how to obtain the default parameter of a function within the decorator?
I have built a series of functions and a decorator as follows:
def check_param(func):
def wrapper(param):
# check the param
check(param)
# then run the function
...
0
votes
2
answers
43
views
How to decorate a python class and override a method?
I have a class
class A:
def sample_method():
I would like to decorate class A sample_method() and override the contents of sample_method()
class DecoratedA(A):
def sample_method():
The ...
0
votes
0
answers
24
views
Monitoring pandas.apply progress
I want to output the progress of the apply() method whenever an API call fails. Here is my code so far:
from googletrans import Translator
translator = Translator()
c = 0
def translate_title(title):...
0
votes
0
answers
36
views
Java CDI: @Decorator gets recursively called
Problem
I'm currently building an application using Quarkus (2.9.2.Final). The project contains multiple modules that depend on each other. The usecase module contains the interfaces for the ...
1
vote
1
answer
48
views
Using functools.wraps function with a little bit different argument list
I want to do something like this:
def need_session(func):
@wraps(func)
def wrapper(*args, **kwargs):
session = SessionLocal()
try:
func(session, *args, **kwargs)
...
0
votes
0
answers
24
views
How to cache a function using a decorator (Python)
I'm studying Python decorators, and I'm trying to write my own cache function (to better understand what caching is about).
This is what I tried:
def hash_table_fun(func):
hash_table = {}
def ...
0
votes
0
answers
12
views
Validate date based on span between dates and boolean
I need to add a validator to my form that validates that the validTo is within 6 month of validFrom when the form is timeLimited.
export class form {
@required()
validFrom?: Date;
@required()
...
0
votes
0
answers
16
views
Creating decorators for class methods
Evening guys.
I'm working on/practicing OOP and decorators.
I am able to construct decorators with functions however, I am struggling to create a decorator to work with class methods.
For example, ...
-1
votes
1
answer
9
views
Python: decorator for mocking gettext during testing
I'm writing a Django app, and I wanted to write a decorator that will mock the _() function during testing, just adding '_translated' after the string to translate
I basically have my decorator to ...
0
votes
0
answers
19
views
Python bypassing @property getter methods ambiguity
I know that this is a badly written code. But why does this behave this way?
class A:
def __init__(self, f, l):
self.first = f
self.last = l
@property
def first(...
0
votes
1
answer
53
views
I expect a single 'hello' as output but it showed 'hello' two times.Why? [closed]
def hello(hi):
print('hello')
@hello
def hi():
pass
hello(hi)
Output:
hello
hello
0
votes
0
answers
51
views
How to get name of a method in NestJS via a decorator?
Related questions I found here:
Get Method Name in TypeScript class - here I've got something useful.
How to get method name in method decorator.
Typescript decorators - get decorator names of a ...
1
vote
1
answer
41
views
python decorators property: getter/setter
I have this code that I'm trying to use decorators getters and setters to append a simple list that receives data from an API.
However the list is coming empty, I've tried out a lot of examples but I ...
-1
votes
0
answers
10
views
OOP - Using decorator inside a class
I will use a decorator inside a class which has instanse-access level but i'm get confused. I tried This link
-1
votes
0
answers
9
views
The difference between calling a decorator and not calling a decorator with arguments [duplicate]
I have this decorator which takes an argument.
from functools import wraps
def repeat(n: int=2):
""" Repeat a function n times """
def wrapper(func):
...
0
votes
1
answer
17
views
How to decorate (overloaded) singledispatchmethod
I want to be able to stack a decorator on singledispatchmethod. If that is not possible, at least on the individual registered functions.
There is probably a simple and elegant solution. I have not ...
1
vote
1
answer
46
views
Change value of variable in Python decorator
from functools import wraps
class EventCounter(object):
def __init__(self, schedules=None, matters=None):
self.counter = 0
self.schedules = schedules
self.matters = ...
0
votes
0
answers
38
views
How do I create custom Lifecycle Hooks for Angular Components
I want to create custom lifecycle hooks for Angular components.
Two examples are that I want to add hooks based on blur / focus of the browser as well as visibility changes on a browser. I'd prefer ...
0
votes
0
answers
16
views
Is the use of this decorator compatible with the design pattern?
I want to print the elapsed time of a method
class MyObject:
def __init__(self, verbose):
self._verbose = verbose
def func(self):
start = time.time()
...
table ...
2
votes
0
answers
42
views
What do I do about not having access to "target" in Stage 3 javascript decorators?
Decorators are now stage 3. https://github.com/tc39/proposal-decorators
I use "target" in the legacy implementation to do lots of things. I've spent a lot of the weekend reading about this ...
0
votes
0
answers
25
views
NetworkXError: random_state_index is incorrect or unable to upgrade the decorator package
I am getting the "NetworkXError: random_state_index is incorrect" error. I have done all of this in administrator mode in Anaconda Prompt, also tried to update directly in Anaconda:
conda ...
0
votes
0
answers
26
views
creating subdomains from list in Flask
Given the list subdomains, how could I programmatically create app.routes with subdomains for each item in the list?
The solution would have the same outcome as below, though the subdomains value will ...
0
votes
1
answer
14
views
Decorator setter is never called
I'm trying to write a lazyLoad decorator in typescript
I have come up with the following
function LazyLoad(target: any, propertyKey: PropertyKey, descriptor: PropertyDescriptor) {
// eslint-...
0
votes
1
answer
52
views
Passing function to a decorator
I am dealing with a problem related to decorators. I want to pass a method with a condition defined in class "Condition" to a decorator. I tried to pass it with the self. command. However ...
0
votes
1
answer
21
views
AttributeError using decorators
I have recently learned about decorators and tried to implement them into my code. In the code below I made a decorator function that loops through data and plots it. This decorator function called &...
0
votes
1
answer
39
views
Python Decorator - Fibonacci Recursive Function - Unexpected Output
I tried to play with using a decorator on a recursive function such as the one that calculates the nth Fibonacci number.
Below is the code I wrote:
class FibList:
# decorator will return a list of ...
0
votes
0
answers
17
views
apply multiple decorators across a code base
What's the pythonic way of applying the same set of decorators across multiple methods in a code base (django tests)?
Example:
from mock import patch
Class A:
@patch('module.function.c')
@...
0
votes
1
answer
35
views
Python decorator which adds a new parameter to a function
I have an addition function with two parameters a and b which simply adds a and b. To round this number, I have made a decorator factory which takes a decimals parameter and round the results of the ...
0
votes
1
answer
22
views
why does a decorated static method in an abstract class returns undefined
I have a decorator and I've used it in some methods in different services and it is working as expected.
I created an abstract class that have a static method and decorated it with the same decorator ...
0
votes
3
answers
50
views
Is it possible to pass arguments to a decorator while calling a function in Python?
Does anyone know if it's possible to pass arguments to a decorator while calling a function in Python ?
Until now, I only saw that at function definition :
@decorator("This is a decorator", ...
1
vote
2
answers
47
views
How to apply the same decorator chain to multiple functions
@extend_schema(
methods=['GET'],
responses={(200, STYLES_MIME_TYPE): OpenApiTypes.BINARY})
@extend_schema(
methods=['PUT'],
request={STYLES_MIME_TYPE: OpenApiTypes.BINARY},
...
0
votes
1
answer
18
views
Angular 9 decorate for required value of a property [duplicate]
I was wondering whether it is possible to create a decorator for a property which checks if value is assigned to it or not yet.
I want to create a required Decorator on a property.
Suppose I have a ...
0
votes
0
answers
32
views
Can I use cache decorator to save result of any function call?
I'm aware that @cache decorator is used as quick way to implement memoization
Is is possible to use it on other contexts, like for deterministic functions (that return the same result provided the ...
-1
votes
1
answer
27
views
How to get in a superclass full names of all methods in subclasses that start with the same two letters in python
I have number of subclasses all of which have number of methods whose names start with "on.."
eg.:
def on_index(self):
raise NotImplementedError()
def on_spiking_intent(self):
raise ...
2
votes
0
answers
51
views
how can I use decorator for method variable inside class in nestjs?
import {isNotEmpty} from "class-validator";
export Service {
create(createdto)
{
const {name,age} = createdto;
@isNotEmpty()
name //using decorator to check whether name is ...
0
votes
1
answer
25
views
How to create a python decorator whose args are the decorated function plus any arbitrary argument(s)
I've created decorators that wrap functions before, but in this instance, I don't need to wrap, so I'm guessing I'm using the wrong paradigm, so maybe somebody can help me figure this out and solve my ...
0
votes
0
answers
10
views
Lifetime of a variable inside a function [duplicate]
In the following code, how is it possible that variable temp is still alive after the call to the Decorate ends?
function Decorate(target, key) {
let temp = target[key];
Object.defineProperty(...
1
vote
0
answers
21
views
How to scan for decorator tags in javascript build?
I wrote a decorator that makes code as obsolete, my question would be, is there a way that I can have a build process that detects this decorator is used in a method, and thus raises some sort of ...