python-decorators

How do I call super in a method decorator in Python 3? [duplicate]

╄→гoц情女王★ 提交于 2019-12-11 09:19:49
问题 This question already has an answer here : Given a method, how do I return the class it belongs to in Python 3.3 onward? (1 answer) Closed 5 years ago . How do I fill in the ??? ? def ensure_finished(iterator): try: next(iterator) except StopIteration: return else: raise RuntimeError def derived_generator(method): def new_method(self, *args, **kwargs): x = method(self, *args, **kwargs) y = getattr(super(???, self), method.__name__)\ (*args, **kwargs) for a, b in zip(x, y): assert a is None

Load module to invoke its decorators

二次信任 提交于 2019-12-11 07:25:45
问题 I have a program consistring of several modules specifying the respective web application handlers and one, specifying the respective router. The library I use can be found here. Excerpt from webapp.service (there are more such modules): from webapp.router import ROUTER @ROUTER.route('/service/[id:int]') class ServicePermissions(AuthenticatedService): """Handles service permissions.""" NODE = 'services' NAME = 'services manager' DESCRIPTION = 'Manages services permissions' PROMOTE = False

Python decorator that returns a function with one or more arguments replaced

元气小坏坏 提交于 2019-12-11 06:51:51
问题 I would like to create a decorator to a set of functions that replaces one or more of the arguments of the functions. The first thought that came to my mind was to create a decorator that returns a partial of the function with the replaced arguments. I'm unhappy with the way the decorated function is called, but even when it's being called "properly", i get a TypeError. Here is some example code: def decor(func, *args, **kwargs): def _new_func(*args, **kwargs): return partial(func, *args, *

Python inheriting docstring errors 'read only'

不羁岁月 提交于 2019-12-11 06:34:35
问题 I have read all the other posts here about this topic but since most of them are quite old I feel better to open a new one with my own problem, since the solutions proposed there don't work for me but I have not seen any complaint in the comments. For instance the solution proposed here gives me the error: AttributeError: 'NoneType' object attribute '__doc__' is read-only The second proposed solution there gives me: TypeError: Error when calling the metaclass bases readonly attribute The only

Inherit property getter documentation

谁都会走 提交于 2019-12-11 06:34:17
问题 The decorator proposed here is able to inherit the docstring for methods but not for properties and getters. I have tried to naively expand it but it seems that docstrings of properties are read-only. Is there any way to inherit those? import types def fix_docs(cls): for name, func in vars(cls).items(): if isinstance(func, (types.FunctionType, property)) and not func.__doc__: print func, 'needs doc' for parent in cls.__bases__: parfunc = getattr(parent, name, None) if parfunc and getattr

AttributeError: 'WSGIRequest' object has no attribute 'request' on OAuth2Decorator

吃可爱长大的小学妹 提交于 2019-12-11 02:47:40
问题 I ran into an issue using Django on Google App Engine trying to access Google API. I want to use the decorator, as described in the docs, but I get the same error over and over again: AttributeError: 'WSGIRequest' object has no attribute 'request' And the StackTrace: Internal Server Error: / Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/core/handlers

Pickle and decorated classes (PicklingError: not the same object)

橙三吉。 提交于 2019-12-11 02:33:42
问题 The following minimal example uses a dummy decorator, that justs prints some message when an object of the decorated class is constructed. import pickle def decorate(message): def call_decorator(func): def wrapper(*args, **kwargs): print(message) return func(*args, **kwargs) return wrapper return call_decorator @decorate('hi') class Foo: pass foo = Foo() dump = pickle.dumps(foo) # Fails already here. foo = pickle.loads(dump) Using it however makes pickle raise the following exception: _pickle

TypeError: 'NoneType' object is not iterable when applying decorator to generator

随声附和 提交于 2019-12-11 01:27:58
问题 I have a decorator function which I want to apply to both normal function and a generator. When applied to the normal function, it works properly. However, when applied to the generator, the iteration loop inside the decorator is executed till the end, but after that the script throws an error: TypeError: 'NoneType' object is not iterable and exits the script. def decor(func): def wrapper(*args, **kwargs): func_name = func.__name__ is_generator = "_generator" in func_name if is_generator: for

Accessing function attribute created in a decorator outside that decorator

廉价感情. 提交于 2019-12-11 01:19:57
问题 I want to count the number of times a given function has been called. So, I made a countcalls decorator to give my functions a __callcount attribute which gets incremented on each call. Simple enough. My issue is getting the __callcount value back out later. Here's my code: import functools def countcalls(f): f.__callcount = 0 @functools.wraps(f) def _countcalls(*args, **kwds): f.__callcount += 1 print(' Called {0} time(s).'.format(f.__callcount)) return f(*args, **kwds) return _countcalls

How to use a context manager inside a decorator and how to pass an object created in decorator to decorated function

陌路散爱 提交于 2019-12-10 18:12:14
问题 I have a test class which requires to do some cleanup at the end. To make sure that the user won't forget to do this, I want to add a context manager to the class. I also have a decorator, inside which I want to use this context manager to create an object of test class and pass it to the decorated function. Is it even possible? This is what I am looking to do: class test: def __init__(self, name): self._name = name print "my name is {0}".format(name) def exit(): print "exiting"