2,520 questions
-2
votes
3
answers
106
views
Python class attributes during definition using functions
I need to set class attributes by calling a function during class definition. A very simplified example would look like the following.
class Mammal():
# Base class provided by internal library
...
1
vote
0
answers
81
views
Pickling error work-around when passing decorators to multiprocessing module
I use the "decorator" idea as way to parameterize functions, but ran into pickling errors when passing these functions as targets to the multiprocessing module. I found a work-around by ...
1
vote
3
answers
114
views
How to get traceback from a module using a decorator?
I have a decorator in the root of a package that should log out information about unexpected exceptions.
from logging import getLogger
from os.path import basename
from traceback import extract_tb
...
1
vote
3
answers
98
views
Inheritance of decorated classes
I'm using Python decorators to implement common functionality across multiple classes. The problem comes when I want the decorated classes to inherit from each other: super() doesn't seem to delegate ...
1
vote
0
answers
88
views
Avoid using global variables whilst allowing a wrapper to modify these variables
I am attempting to create a decorator which prints the current call chain into the terminal in a similar format to the windows tree command. An object of my class type is tied to each function as they ...
2
votes
1
answer
56
views
How to access parent decorator variable in child decorator
I am working on a decorator. To avoid duplicating code I am inheriting a parent decorator which has a nonlocal variable defined. I am not able to get the exact behaviour in my child decorator as I am ...
0
votes
2
answers
114
views
Adding decorator to a python class
I have a few methods that require a certain condition to be applied to function properly. To avoid code repetition I've created a decorator to check if this condition is applied and only then execute ...
6
votes
2
answers
147
views
How to use @wraps with decorator factories
I have a decorator factory which just multiplies some given numbers.
from functools import wraps
def multiply(numbers):
def decorator(f):
def wrapper(*args, **kwargs):
num1 = numbers[0]
...
3
votes
1
answer
244
views
Timefold Python project terminates on encountering Timefold decorators
I have been working with Timefold in Python for a while and wrote a setup manual for a Timefold project. When testing this setup manual on another device we ran into a problem. It doesn't seem to ...
2
votes
1
answer
569
views
Why does Pyright report an incompatible method override when using a decorator with multiple parameters?
I'm experiencing a type checking error with Pyright when using a decorator with a method that overrides another method. The error occurs only when the method has two parameters (self and another ...
2
votes
1
answer
61
views
Wrap class method with argument(s) only once
There are two classes and I want to wrap item.foo method only once, to prevent cache = {param1: 'param_value'} being reinited
class Foo:
_count = 0
def foo(self, param2):
self._count +...
1
vote
1
answer
108
views
Type annotate decorator that changes decorated function arguments
I want to design a decorator that will allow the wrapped method to take a float or a numpy array of floats. If the passed argument was a float then a float should be returned and if it was a numpy ...
3
votes
2
answers
191
views
How to add function parameter kwargs during runtime?
I have hundreds of functions test1, test2, ...
Function testX may or may not have kwargs:
def test1(x, z=1, **kwargs):
pass
def test2(x, y=1):
pass
def test3(x, y=1, z=1):
pass
...
and I ...
0
votes
1
answer
84
views
Why Python type infer error for decorator
Type infer error for decorator
class with __get__ not properly identified
type with Generic lose Type[]
The following are the comparisons of several scenarios.
from typing import TypeVar, Callable, ...
0
votes
1
answer
182
views
Using python decorators associated with an instance level object
I am trying to create a decorator which enables me to register callback functions to an instance of ClassB. I would like to use this decorator in other classes within my program (eg. ClassA) but want ...
1
vote
1
answer
337
views
PySide6 signal not emitting properly when passed to decorator
I have this decorator in python 3.11 that sends a signal encoding the arguments to a function call that it decorates, here:
def register_action(signal=None):
def decorator(func):
def ...
1
vote
1
answer
62
views
Django decorator import issue: 'cannot import name' when used in views.py
when trying to start the server it cannot find the decorator
from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required
...
@staff_member_required
def ...
0
votes
1
answer
96
views
How do I find classes that are decorated by a given decorator in Python?
I am trying to do something like SpringBoot @Component scan to search for classes that are decorated with Temporal @worfklow.defn and @activity.defn so I can automatically register them to the worker ...
0
votes
0
answers
71
views
Writing decorator adding callables taking objects of generic type to instance list
I want to create a custom Collection (FnColl) that is specific for an ObjectType T and holds a list of Callables, each taking an object of type T and returning any value.
class FnColl[T]:
def ...
0
votes
0
answers
34
views
RocketPy: Can't access Flight.x, Flight.y, Flight.z values
The bug I'm experiencing is I am trying to access the values of Flight.x, Flight.y and Flight.z. I checked the documentation and Flight.x and Flight.z are indexed differently to Flight.y. I want to be ...
0
votes
1
answer
98
views
Why does inspect identify decorated methods as functions instead of methods in Python?
I'm working on a Python project where I'm using decorators to wrap functions and methods with some logic. However, I've encountered an issue where inspect identifies the decorated methods as functions ...
0
votes
0
answers
33
views
Why is request.user not being populated in Django when using custom JWT middleware?
I'm implementing custom JWT authentication in Django and I'm using middleware to decode the JWT token and assign request.user to the authenticated user. However, when I try to access request.user ...
0
votes
1
answer
190
views
How to gracefully skip pytest tests if optional dependencies are not installed?
I have a Python package with optional dependencies defined in pyproject.toml. I want to run pytest while ensuring that specific tests are executed only if the relevant optional dependencies are ...
0
votes
0
answers
61
views
Add an optional keyword argument to the signature of a python function?
I have a python decorator, apply_suffix which adds a suffix keyword argument to a python function.
import functools
def add_suffix(func):
@functools.wraps(func)
def wrapper(*args, suffix: str =...
0
votes
0
answers
39
views
Profile selected functions in Python
I can profile and visualize my entire application with:
python -m cProfile -o program.prof my_program.py
snakeviz program.prof
Is it possible to write a decorator that will profile only some ...
2
votes
1
answer
121
views
Calling a wrapped static method using self instead of class name passes self as arg
This question is related to Calling a static method with self vs. class name but I'm trying to understand the behavior when you wrap a static method so I can fix my wrapper.
For example:
import ...
0
votes
2
answers
43
views
How to dynamically choose between two methods with parameters using a property in Python
I have a Python class that needs to dynamically choose between two methods based on a condition. Both methods take parameters. I want to use a property to determine which method to call. How can I ...
1
vote
1
answer
694
views
Python typing of Callable with Concatenate and ParamSpec for child class functions in decorator?
I feel I'm not understanding something and don't know the correct way to typehint this.
I've got a parent class and a child class. I'm trying to create a decorator with ParamSpec so I gain access to ...
0
votes
1
answer
324
views
How can I convert a TypeVarTuple to a ParamSpec?
(I am almost certain the wording of the question does not make sense, but I have yet to find a better one.)
I have the following code that I want to type-check:
from collections.abc import Callable
...
0
votes
2
answers
52
views
How can getattr() respect python class properties?
I have a class that performs some useful job in my project
class Test:
def __init__(self):
self.__value = None
def set_value(self, value):
print(f"set_value(): value={...
0
votes
1
answer
178
views
Internal function call in FastAPI / Parameter that I can set only inside the FastAPI app
I wrote my own session logic and use the following decorator to check the request:
def require_session(func):
@wraps(func)
async def wrapper(*args, **kwargs):
request = kwargs['request'...
0
votes
4
answers
119
views
Python: Decorator to count swaps in sorting algorithms
I want to write a decorator that will count the number of swaps in a sorting algorithm. I created a swap function to swap numbers and a decorator that counts each call to this function. The issues I'...
0
votes
2
answers
125
views
How to combine multiple @staticmethod decorators into a single one
I want to combine multiple @statimethod decorators (let's call them decorator_1, decorator_2, etc.) into a single @staticmethod combined_decorator.
For my use case, I need the decorators to be able to ...
1
vote
0
answers
120
views
Type hint annotation for decorator around sync/async function
What is the correct way to specify a type annotation for a decorator that can be applied to both sync and async functions? I specify the type for the received function as type FuncType[**P, R] = ...
0
votes
2
answers
108
views
Is there a way to find undecorated classes/functions in a Python module?
I'm trying to write a tool which will help me find implementation bugs in a large existing python code base that makes heavy use of decorators.
Lets say I have a file, rules.py:
manager = RuleManager()...
0
votes
0
answers
89
views
Decorator and Class/Instance Methods
I have a class to preload data into cache when an event happens. I want to register loader functions with a decorator and an event key, so that when the event fires, I can execute the functions.
from ...
-1
votes
3
answers
104
views
Re-decorate a python (class) decorator [duplicate]
I'd like to create a decorator that basically wraps an already existing decorator that has parameters, such that the new decorator acts like the old one with some of the arguments supplied.
...
0
votes
0
answers
63
views
Decorator causes a problem AttributeError: 'NoneType' object has no attribute
I was working on my project about matrixes. I write method that multiply every element on number and function that sums matrices:
class SquareMatrix():
def __init__(self, rows, random=False, *args)...
0
votes
1
answer
159
views
Optimizing dynamic programming solution for Abbreviation problem- Hackerrank
So I personally favor coding dynamic programming solutions using a top-down approach. Especially in python because it lends itself to a rather easy recursive implementation using the cache decorator, ...
1
vote
1
answer
60
views
Decorate instance methods with decorator class that replaces method with class instance
I would like to be able to decorate instance methods with a class Step such that the methods are replaced by a Step object. At the same time, I'd like to have the option be able to instantiate a step ...
1
vote
1
answer
189
views
Python annotate adding class members in __get__
I want to create a decorator that adds a member to the decorated class
that is instance of outer class.
In this case, decorator memberclass adds attribute self to the instance of class y that is of ...
-1
votes
2
answers
148
views
How can I use decorators to modify the behavior of multiple functions?
I’m learning about decorators in Python and would like to use them to modify the behaviour of several more complex functions in my code. Specifically, I want to:
Log the execution time for each ...
0
votes
1
answer
88
views
How to get response content from a Response() object in a view decorator?
Let's say I have a decorator that can be applied to a DRF class based View.
A basic version of the decorator i have is as follows:-
`class LogRequest:
def __init__(self, log_success=True, ...
2
votes
2
answers
98
views
Python exception stack trace not full when function is wrapped
I have two files t.py:
import functools
import traceback
def wrapper(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
...
1
vote
1
answer
249
views
How to split python-decorated API router methods in different files
I cannot find a clean way to structure a python API project that splits the routes of a module (/invoices for this example) into different files, when using a decorator approach for the routing ...
0
votes
2
answers
184
views
How to override the help text of a shared python click option?
I am using python click options that are shared by multiple commands, as described at https://stackoverflow.com/a/77732441.
Is there a simple way to customize the help= text of the list option in the ...
1
vote
1
answer
199
views
How to deduce whether a classmethod is called on an instance or on a class
I'm writing a logger decorator that can be applied to, among others, classmethods (and theoretically any kind of function or method). My problem is that their parametrization changes according to ...
1
vote
1
answer
2k
views
Using Jax Jit on a method as decorator versus applying jit function directly
I guess most people familiar with jax have seen this example in the documentation and know that it does not work:
import jax.numpy as jnp
from jax import jit
class CustomClass:
def __init__(self, x:...
1
vote
1
answer
54
views
Having trouble seeing the motive for decorators in *simple* examples
I've surfed some tutorials online about decorators. I'm having trouble seeing their benefit for simple examples. Here is a common example of a function crying out to be decorated, taken from this ...
2
votes
1
answer
74
views
Python class mimic makefile dependency
Q: Is there a better way to do this, or the idea itself is wrong
I have a processing class that creates something with multiple construction steps, such that the next function depends on the previous ...