python-decorators

`__set_name__` hook manually added to `functools.wraps()` descriptor instance never called

`__set_name__` hook manually added to `functools.wraps()` descriptor instance never called Question: I’m trying to add a __set_name__ hook to the descriptor produced by functools.wraps inside a decorator, but it is never called and I don’t see any error messages: import functools def wrap(fn): """Decorator.""" @functools.wraps(fn) def w(*args, **kwargs): return fn(*args, **kwargs) # This never gets …

Total answers: 1

python decorate class method sending a parameter to the decorator

python decorate class method sending a parameter to the decorator Question: I have the following class in python: class MatrixOfCarriers(DataLoader): def load_data(self): brands = self.brands try: data = self._load_data() print("’Carrier Matrix’ data loaded successfully.n") except Exception as e: print( "nCouldn’t load ‘Carier Matrix’ data due to the following " + "error: ‘{}’".format(str(e)) ) raise e …

Total answers: 1

Is there a way to create multiple decorators with the same naming convention in Python?

Is there a way to create multiple decorators with the same naming convention in Python? Question: We have a few decorators to register functions and classes inside imported files, that look like the following: def register_crawler(func): register(func, "crawler") return func def register_model(func): register(func, "model") return func def register_generator(func): register(func, "generator") return func In each case, …

Total answers: 1

How to get the arguments of a decorator function?

How to get the arguments of a decorator function? Question: I have a command with a decorator @commands.has_role("admin") and I need to get that role. This is what I have tried: filtered = await self.filter_commands(self.context.bot.commands, sort=True) checks = [command.checks for command in filtered] for check in checks: for c in check: print(c.role) but returns AttributeError: …

Total answers: 1

How to check for class attribute initialization with a decorator?

How to check for class attribute initialization with a decorator? Question: Consider the following code. def check(data): def decorator(function): def wrapper(*args, **kwargs): if data not in ["toto", "tata"]: raise ValueError("Wrong argument") result = function(*args, **kwargs) return result return wrapper return decorator class Foo: @check def __init__(data): self.data = data Foo(data="t") I would like to decorate …

Total answers: 1

Why does a json file behave like this?

Why does a json file behave like this? Question: There is a function (rui) that takes the number num and returns the tenth power of num. Task: to write a decorator that will cache the outputs from this function so that if a num that has already been submitted is fed to the input, the …

Total answers: 2

Why is my Python decorator class's __get__ method not called in all cases?

Why is my Python decorator class's __get__ method not called in all cases? Question: So I’m trying to implement something akin to C# events in Python as a decorator for methods: from __future__ import annotations from typing import * import functools def event(function: Callable) -> EventDispatcher: return EventDispatcher(function) class EventDispatcher: def __init__(self, function: Callable) -> …

Total answers: 1

Keep decorator on override method

Keep decorator on override method Question: I’ve got a parent class with a method used many times and override all the time. This method has a decorator. I would like to reuse the decorator each time I override the methode without using super() or rewrite de decorator def decorator(method): def wrapper(self, *args, **kwargs): print("how are …

Total answers: 1

Python: use the decorator to pass an extra parameter to the function

Python: use the decorator to pass an extra parameter to the function Question: I have a function than depends on db connection. This function has a lot of return statements, of this kind: def do_something_with_data(db: Session, data: DataClass): db = Session() if condition1: db.do_something1() db.close() return if condition2: db.do_something2() db.close() return if condition3: db.do_something3() db.close() …

Total answers: 1

TypeVar inference broken by lru_cache decorator

TypeVar inference broken by lru_cache decorator Question: python’s TypeVar inference broken when using lru_cache decorator. For example, after applying mypy the following example, only function with lru_cache causes error like: main.py:14: error: Incompatible types in assignment (expression has type "T", variable has type "int") Found 1 error in 1 file (checked 1 source file) and …

Total answers: 1