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,942
questions
0
votes
0
answers
12
views
Angular 12 - @Input & @Output vars do not work
When using @Input or @Output communication between newlly created Components, the Flow simpl doesnt work. It is new, before that things worked just fine. I have not instaled anything new, Versions of ...
-1
votes
0
answers
15
views
How to Use Original Function's Internal Variables with Python Decorators [duplicate]
I'm learning to use Python decorators, and I encountered an issue while using decorators. Here's the current example:
# Support Vector Machine (Linear)
def svc_linear():
# Create an SVM classifier
...
1
vote
1
answer
28
views
Interplay of argument injecting decorators and pytest fixtures
I have a decorator that can inject an argument into a function, which works fine. However, when I want to use it on a test function, things get messed up with pytest fixtures. Is there any way to fix ...
-2
votes
0
answers
24
views
Is there an existing Flutter widget that matches the bottom of iphone homescreen [closed]
Is there a specific widget I should use that gives the rounded box behind the SmoothPageIndicator? I want it to dynamically shrink and expand. Would a container be the best option?
0
votes
1
answer
56
views
python decorators to valid user input of different types
I am trying to build a class that has different user inputs. I want to use the decorators that I have written to automatically valid in the initialisation.
The ValidationDecorators is the class that ...
0
votes
2
answers
36
views
Python decorator with a function that receives a parameter
Decorator is not working as intended
I was trying to understand more about decorators, so I searched and got many videos that made this exact function:
def tictoc(func):
def wrapper():
t1 =...
1
vote
1
answer
16
views
Dynamic list of decorators
I would like to prepare very adjustable components using decorators (aka plugin system).
I found the great solution with decorator factory, but I see that factory function returns a single decorator.
...
0
votes
0
answers
27
views
How to dynamically fill components with content
I need your help. I have four different components
content.component - the component that we will fill with unique content and it will display this unique content
show-components.component - a ...
1
vote
1
answer
50
views
Conflicting C# generic constraints
I am implementing a DynamoDBContext decorator that will perform sensitive data tokenization on objects when a value is written or loaded. The class must implement IDynamoDBContext so that it can be ...
0
votes
2
answers
53
views
How to assign custom names to properties?
I'm using a PLC shield (Kontron Pixtend) to read and control pneumatic valves and switches. A Python API (class) is provided. All runs on a Raspberry Pi. Outputs/inputs of the PLC shield are ...
0
votes
1
answer
28
views
How does my decorator-class apply the signatur of the passed function?
I have created a functionlity so that the initialization of a class can be done in another class without replicating the whole method. It works, but I dont understand why.
I have several device-...
0
votes
2
answers
58
views
Passing "self" to a decorator in a class
I am trying to imitate the behavior of flask's decorator, like so:
app = Flask(__name__)
@app.route("/")
...
However, I cannot seem to pass "self". Here's an example:
class A:
...
0
votes
2
answers
62
views
Decorator Design Pattern - Example
I am trying to understand Decorator Design Pattern.
Wonder what is the best way to decorate fields values in below example?
Am I using decorator pattern correctly? If not how can I improve it?
public ...
1
vote
2
answers
182
views
Python 3.10 type hinting for decorator to be used in a method
I'm trying to use typing.Concatenate alongside typing.ParamSpec to type hint a decorator to be used by the methods of a class. The decorator simply receives flags and only runs if the class has that ...
0
votes
0
answers
34
views
MyPy Type Check Decorated Class
This is a simplified version of a class decorator I've written. It functions as expected, but mypy doesn't like it, complaining that FormB and FormA do not inherit from FormBase. How do I convince ...
0
votes
1
answer
42
views
Decorator pattern in VBA
Is there anyway to achieve the "Decorator-pattern" such as below in Excel VBA ?
Sub runner(subroutine)
MsgBox ("Decoration Before")
Call subroutine
MsgBox ("Decoration After&...
2
votes
1
answer
46
views
Modifying class decorator on class with property decorator
I have a bunch of data classes that I'm trying to build from a dictionary of parsed XML. The keys in this XML have been obfuscated so I've had to go through tedious amounts of documentation, written ...
0
votes
0
answers
27
views
PyCharm does not recognize the return type of a decorated function?
I am trying to decorate a method of a python class:
from typing import Any, Callable, TypeVar
T = TypeVar('T')
def my_decorator(func: Callable[..., T]) -> Callable[..., T]:
@functools.wraps(...
0
votes
1
answer
54
views
Creating a time measurement decoration for a recursive function with memoization
I'm trying to create a decorator to measure the time of a function:
def time_dec(func: Callable):
def inner(*args, **kwargs):
t1 = timer()
func(*args, **kwargs)
print(timer(...
0
votes
1
answer
195
views
How can I create a decorator with Mapstruct in my Spring boot application?
I have a Spring boot application where auto component scan is enabled and mapstruct seems to be set up correctly, since it works on basic mappings created on interfaces, but I can't seem to add a ...
0
votes
0
answers
21
views
Workaround for calling `open()` in `__del__()` for a function decorator
I am writing a function decorator to perform profiling of a function, it stores information about the function during execution and outputs the information into a log file. The implementation causing ...
0
votes
1
answer
28
views
Explicitly delete variables within a function if the function raised an error
A particular problem with unit tests. Many of my test function have the following structure:
def test_xxx():
try:
# do-something
variable1 = ...
variable2 = ...
except ...
0
votes
1
answer
49
views
Decorate all functions of a Python class while being able to access the class attributes within the decorator
I've got a class and would like to apply a decorator to all functions within that class without having to add a function decorator to every single function.
I know that there are solutions like the ...
0
votes
1
answer
67
views
Mixin design to extend template parameter struct for various applications
I have a templated class that accepts structs as parameters (there is a reason for this that I won't get into here, but the design requires it). I am trying to generate a mixin design pattern (static ...
0
votes
1
answer
23
views
Unable to access base class methods in derived class when using method decorators in TypeScript
Can someone help me understand following things as when I am using method decorator in TS -
Why Base class method base is not callable in Derived class?
Why Base class property val is undefined even ...
0
votes
2
answers
67
views
How to limit an input parameter's value range in a python way?
If I design a function like
def f(a, b):
...
a must be in [1,2,3]. If I pass 4 to parameter a, it should raise an exception. Is there a pythonic way to limit the value range of a function argument?
...
0
votes
1
answer
53
views
How to create custom decorator in nestJS to implement simple encryption of the request payload from the body of an API request endpoint?
Api inside the controller
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { EncryptionService } from './encryption.service';
import { Decrypt } from 'src/common/decrypt....
2
votes
0
answers
26
views
What is a Host element when we using @HostListener in component?
I know what the host element for a directive is the element in which the directive applies. But I don't understand what is the host element for a component.
My code is working, but I can't get how it ...
0
votes
0
answers
18
views
I am trying to make a custom flask decorator for a multi login system
I and making a flask app for appointments. I made a admin page and sudo admin page for different levels of login and different levels of authorities. For the admin section and page access after login ...
0
votes
0
answers
44
views
Decorator that can be used in class constructor in Nest.js and uses injectables itself
Using Nest.js to inject dependencies, how can a custom decorator be created that itself injects and uses services, and that can be called in a class constructor? I'm looking for a generic answer, ...
1
vote
1
answer
139
views
Lit TypeScript decorator issue
I try to get into TypeScript by writing TS based Lit Elements, refactoring a very small project of mine.
However it starts to get frustrating since I don't see what's wrong with this code since it's ...
1
vote
1
answer
17
views
Replace Response.Headers.Add with method attribute decorator
In a Controller, I have this method:
public async Task<IActionResult> DownloadReportAsync()
{
var file = GetFile();
Response.Headers.Add("Access-Control-Expose-Headers", "...
0
votes
0
answers
45
views
TS: What is the best way of getting decorator properties in children DTO of DTOs?
I have two DTOs that looks like this
//MyDTO.controller.ts
export class MyDTO{
@CustomDecorator
readonly PropertyA: string
readonly PropertyB: MyDTO2
}
//MyDTO2.controller.ts
export class ...
0
votes
1
answer
15
views
How do I call a function from my library that is marked with a decorator?
How do libraries call functions marked with decorators?
example:
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
How is this implemented inside the library?
I ...
1
vote
0
answers
51
views
Nest Swagger: How to defined a properties of an object with generic type?
I'm doing a pagination common.
I want to define "order by" properties as a key in generic T
export class BasePagination<T> {
@DtoNumber({ required: true })
limit: number;
@...
1
vote
1
answer
44
views
Python decorator with threading / threading behaviour
I needed to display a waiting message for the user while a function is doing its work (in this case specifically, waiting for a response from Google's speech-to-text service). I therefore used ...
3
votes
3
answers
105
views
Calling another member decorator from another member decorator in Python 3
I am trying to re-use a member function decorator for other member function decorator but I am getting the following error:
'function' object has no attribute '_MyClass__check_for_valid_token'
...
0
votes
2
answers
84
views
How to correctly type-hint a function with `pyqtSlot()` decorator inside `QRunnable` class?
Status:
I'm learning how to use concurrency/threads within PyQt library from here www.pythonguis.com. Below is the simplified/part of code from this tutorial.
I want strict type hinting in my code. ...
-2
votes
1
answer
32
views
i tried write the first code in a different way. first is okay second also runs but i got a " nontype object is not callable error". why is that?
in this python code here i get error "nonetype object is callable". why is that? thanks
`#firstcode
def decor(func):
def wrap():
print("============")
func()
...
0
votes
0
answers
17
views
Pattern for defining defaults arguments without duplication and keeping prototype
I've noticed that I regularly have the following pattern:
A class that on instantiation sets default values
A function that allows one to change some of these default values
A simple example that ...
0
votes
2
answers
60
views
Constructor Function Type for Class Decorators
I have a class decorator where I want to pass type for a constructor function parameter to avoid linting error,so I can't pass type as Function.For Example-
function Student(config) {
return ...
1
vote
1
answer
37
views
Decorating JsonLd ItemNormalizer
In API Platform, I am trying to decorate the service api_platform.jsonld.normalizer.item (class ApiPlatform\JsonLd\Serializer\ItemNormalizer).
I notice this is causing some strange behavior in my ...
0
votes
0
answers
15
views
inspect getsource didn't response with annotation on a class
For exampel I have a class in Python:
def dec(clz):
return clz
@dec
class Test:
pass
when I use insepct.getsource(Test) in python 3.8, the souce code has no @dec
But sourcecode will contain @...
5
votes
0
answers
51
views
How to Prevent Nested Decorators in Autofac When Using Interface Inheritance?
I have a .NET 7.0 application where I am using Autofac as my DI container. I have two interfaces IReadonlyRepository<T> and IRepository<T>, where IRepository<T> inherits from ...
-3
votes
1
answer
45
views
What is this 'nonlocal' keyword is doing is this decorator? [closed]
I created this decorator to save the output of a function to a csv file (so the team can easily read it).
def save_to_csv(directory, file_name = None):
def decorator(func):
def wrapper(*...
1
vote
0
answers
13
views
Exporting decorated Class in TypeScript
I have a TypeScript class and added a decorator over methods to measure their latency.
If I export the class directly I get the error:
export class DB{
@latency
public async writeToDB(itemID:string){
....
0
votes
0
answers
93
views
Unable to resolve signature of class decorator when called as an expression. TypeORM
I want to create Typeorm entity, but TS i've got this error:
Unable to resolve signature of property decorator when called as an expression. Argument of type 'undefined' is not assignable to parameter ...
0
votes
0
answers
41
views
Typescript Decorator to pass method reference to invoke method somewhere else
Code Here
High-Level Goal: I have been tasked to create a ridiculously easy way to expose methods of a class to a Supervisor class that can invoke them at any time. The reason for such a system is so ...
0
votes
0
answers
16
views
Wrap any function or method by container class using a decorator [duplicate]
In Python, I would like to wrap both decorated functions or methods into a container class holding additional information and generally mark functions as "externally callable".
Given this ...
0
votes
2
answers
48
views
Using pytest fixture in test decorator
i'm writing some unit tests that need to be run in temporary directory, but after performing actions, cwd should be set to original one.
So, to remain consistent with rest of the codebase, i'm using ...