python-decorators

Applying a decorator to an imported function?

China☆狼群 提交于 2019-11-28 23:53:16
问题 I want to import a function: from random import randint and then apply a decorator to it: @decorator randint I was wondering if there was some syntactic sugar for this (like what I have above), or do I have to do it as follows: @decorator def randintWrapper(*args): return random.randint(*args) 回答1: Decorators are just syntactic sugar to replace a function object with a decorated version, where decorating is just calling (passing in the original function object). In other words, the syntax:

Python functools lru_cache with class methods: release object

耗尽温柔 提交于 2019-11-28 18:42:50
问题 How can I use functools' lru_cache inside classes without leaking memory? In the following minimal example the foo instance won't be released although going out of scope and having no referrer (other than the lru_cache). from functools import lru_cache class BigClass: pass class Foo: def __init__(self): self.big = BigClass() @lru_cache(maxsize=16) def cached_method(self, x): return x + 5 def fun(): foo = Foo() print(foo.cached_method(10)) print(foo.cached_method(10)) # use cache return

How do I avoid the “self.x = x; self.y = y; self.z = z” pattern in __init__?

痞子三分冷 提交于 2019-11-28 15:15:26
I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should the class inherit from namedtuple instead? Edit: If you have python 3.7+ just use dataclasses A decorator solution that keeps the signature: import decorator import inspect import sys @decorator.decorator def simple_init(func, self, *args, **kws): """ @simple_init def __init__(self,a,b,...,z) dosomething() behaves like def __init__(self,a,b,...,z) self.a = a self.b = b ... self.z =

Python @property decorator not working

徘徊边缘 提交于 2019-11-28 13:29:37
Could anyone find a problem with this @property decorator? I cannot seem to get it to assert correctly. I'm sure I'm doing some really simple thing wrong, but can anyone point my tired eyes in the right direction please? class A: def __init__(self): self.a = 0 self._b = 0 @property def b(self): return self.b @b.getter def b(self): if self._b is None: return 0 return self._b @b.setter def b(self, val): self._b = (val * 20) def test_getter_setter(): obj = A() obj.a = 1 #obj.b = 2 print obj.a, obj.b obj.b = 2 print obj.a, obj.b assert obj.b == 40 test_getter_setter() The @property decorator only

list @property decorated methods in a python class

折月煮酒 提交于 2019-11-28 12:34:17
Is it possible to obtain a list of all @property decorated methods in a class? If so how? Example: class MyClass(object): @property def foo(self): pass @property def bar(self): pass How would I obtain ['foo', 'bar'] from this class? Anything decorated with property leaves a dedicated object in your class namespace. Look at the __dict__ of the class, or use the vars() function to obtain the same, and any value that is an instance of the property type is a match: [name for name, value in vars(MyClass).items() if isinstance(value, property)] Demo: >>> class MyClass(object): ... @property ... def

Python - Decorators

微笑、不失礼 提交于 2019-11-28 10:50:33
I'm trying to learn Decorators . I understood the concept of it and now trying to implement it. Here is the code that I've written The code is self-explanatory. It just checks whether the argument passed in int or not. def wrapper(func): def inner(): if issubclass(x,int): pass else: return 'invalid values' return inner() @wrapper def add(x,y): return x+y print add('a',2) It's throwing error saying global name 'x' is not defined . I understand that it is not defined under inner , but didnt know how to rectify this code? Where I'm going wrong? sloth Your decorator should look like: def wrapper

Using classes as method decorators [duplicate]

风流意气都作罢 提交于 2019-11-28 10:32:38
This question already has an answer here: How can I decorate an instance method with a decorator class? 3 answers While there are plenty of resources about using classes as decorators , I haven't been able to find any that deal with the problem of decorating methods . The goal of this question is to fix that. I will post my own solution, but of course everyone else is invited to post theirs as well. Why the "standard" implementation doesn't work The problem with the standard decorator class implementation is that python will not create a bound method of the decorated function: class Deco: def

Callable object decorator applied to method doesn't get self argument on input

一个人想着一个人 提交于 2019-11-28 10:23:40
import functools class Decor(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): def closure(*args, **kwargs): print args, kwargs return self.func(*args, **kwargs) return closure(*args, **kwargs) class Victim(object): @Decor def sum(self, a, b): return a+b v = Victim() v.sum(1, 2) Results in: (1, 2) {} Traceback (most recent call last): File "test.py", line 19, in <module> v.sum(1, 2) File "test.py", line 11, in __call__ return closure(*args, **kwargs) File "test.py", line 10, in closure return self.func(*args, **kwargs) TypeError: sum() takes exactly 3

How to skip a pytest using an external fixture?

[亡魂溺海] 提交于 2019-11-28 09:45:43
Background I am running a py.test with a fixture in a conftest file . You can see the code below(this all works fine): example_test.py import pytest @pytest.fixture def platform(): return "ios" @pytest.mark.skipif("platform == 'ios'") def test_ios(platform): if platform != 'ios': raise Exception('not ios') def test_android_external(platform_external): if platform_external != 'android': raise Exception('not android') conftest.py import pytest @pytest.fixture def platform_external(): return "android" Problem Now I want to be able to skip some tests that do not apply to my current test-run. In my

Python decorator @func().attribute syntax error

余生长醉 提交于 2019-11-28 07:58:56
问题 I tried to find an answer here, but could not. @obj.func # works @obj.func(**kwargs) #works @obj.func1(**kwargs).func2 #-> syntax error I do not understand why the third form is a SyntaxError, it seems for me that is not violating any python syntax and it is clear for me what the user want to do (see example below). I looked at pep 0318 of decorator implementation but didn't find any answers. Here bellow, would be an example of use: class ItemFunc(object): def __init__(self, fcall=None, *