Category : functools

I’m using Pydantic’s BaseModel for creating my working class. I also have custom methods other than the methods with validators. I need to use singledispatchmethod decorator from functools with the custom function. For example, class Foo(pydantic.BaseModel): name: str bar: int baz: int @functools.singledispatchmethod def handle(self, command: Command) -> CommandResult: pass @celery.task def add(a: int, b: ..

Read more

docs.python.org says that functools.partial is roughly equivalent to: def partial(func, /, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = {**keywords, **fkeywords} return func(*args, *fargs, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc (Note: / is used to denote func as a positional-only argument of partial. See [1].) If I understand correctly, when ..

Read more

The simple way to measure the execution time of a function with function decorator: def timeit(func): import time def call_func(*args, **kwargs): begin_time = time.time() func(*args, **kwargs) end_time = time.time() run_time = end_time – begin_time print(‘it cost {} seconds ‘.format(run_time)) return call_func @timeit def bar(): time.sleep(3) bar() can show the execution time ,but bar point to ..

Read more

I made up this simple, contrived example of some code I ran into at work. I’m trying to better understand why slow_function_1 (+ the way its decorators are structured) would cache function results properly, but the decorator applied to slow_function_2 would not. In this example, I’m trying to access cache information after calling the method; ..

Read more

I have a higher order function with required argument required, function func, and arguments for func *args. However, func may take required as an argument. def higher_order_func(required, func, *args): func(*args) # This MAY take `required` do_something_with(required) This works fine but is not pythonic when I supply some func which takes required as an argument. def ..

Read more

I have this class method decorator from https://stackoverflow.com/a/46361833/5316326 that accepts parameters. How can I list the class methods that use this decorator on the created object? from functools import update_wrapper, partial def my_decorator(name): class MyDecorator(object): def __init__(self, func): update_wrapper(self, func) self.func = func def __get__(self, obj, objtype): """Support instance methods.""" return partial(self.__call__, obj) def __call__(self, ..

Read more