decorator

Python closure function losing outer variable access

与世无争的帅哥 提交于 2019-12-21 07:28:31
问题 I just learned python @ decorator, it's cool, but soon I found my modified code coming out weird problems. def with_wrapper(param1): def dummy_wrapper(fn): print param1 param1 = 'new' fn(param1) return dummy_wrapper def dummy(): @with_wrapper('param1') def implementation(param2): print param2 dummy() I debug it, it throws out exception at print param1 UnboundLocalError: local variable 'param1' referenced before assignment If I remove param1 = 'new' this line, without any modify operation

Inheriting from decorated classes

☆樱花仙子☆ 提交于 2019-12-21 05:48:09
问题 I'm trying to decorate a class with another class. I also want to inherit from the decorated class, but I get some errors. Here's my code: class Decorator: def __init__(self, decorated): pass @Decorator class Foo: pass class Goo(Foo): pass The error I get when I try to subclass from Foo is this: Traceback (most recent call last): File "test.py", line 9, in class Goo(Foo): TypeError: __init__() takes exactly 2 positional arguments (4 given) By adding another init function to Decorator ... def

wrapping class method in try / except using decorator

时间秒杀一切 提交于 2019-12-21 05:21:08
问题 I have a general purpose function that sends info about exceptions to an application log. I use the exception_handler function from within methods in classes. The app log handler that is passed into and called by the exception_handler creates a JSON string that is what actually gets sent to the logfile. This all works fine. def exception_handler(log, terminate=False): exc_type, exc_value, exc_tb = sys.exc_info() filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1] log.error(

python decorator to display passed AND default kwargs

我是研究僧i 提交于 2019-12-21 05:03:10
问题 I am new to python and decorators and am stumped in writing a decorator which reports not only passed args and kwargs but ALSO the unchanged default kwargs. This is what I have so far. def document_call(fn): def wrapper(*args, **kwargs): print 'function %s called with positional args %s and keyword args %s' % (fn.__name__, args, kwargs) return fn(*args, **kwargs) return wrapper @document_call def square(n, trial=True, output=False): # kwargs are a bit of nonsense to test function if not

Get Python function's owning class from decorator

☆樱花仙子☆ 提交于 2019-12-21 04:33:10
问题 I have a decorator in PY. It is a method and takes the function as a parameter. I want to create a directory structure based based on the passed function. I am using the module name for the parent directory but would like to use the classname for a subdirectory. I can't figure out how to get the name of the class that owns the fn object. My Decorator: def specialTest(fn): filename = fn.__name__ directory = fn.__module__ subdirectory = fn.__class__.__name__ #WHERE DO I GET THIS 回答1: If fn is

Can I use a decorator to mutate the local scope of a function in Python?

怎甘沉沦 提交于 2019-12-21 04:13:32
问题 Is there any way of writing a decorator such that the following would work? assert 'z' not in globals() @my_decorator def func(x, y): print z EDIT: moved from anwser In answer to hop's "why?": syntax sugar / DRY. It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the values of x & y. I have lots of functions which do related things, and I don't want to do have to write z1, z2, z3=calculate_from(x, y) at the beginning of every single function - I'll get it wrong

Writing a CherryPy Decorator for Authorization

为君一笑 提交于 2019-12-21 01:18:11
问题 I have a cherrypy application and on some of the views I want to start only allowing certain users to view them, and sending anyone else to an authorization required page. Is there a way I can do this with a custom decorator? I think that would be the most elegant option. Here's a basic example of what I want to do: class MyApp: @authorization_required def view_page1(self,appID): ... do some stuff ... return html def authorization_required(func): #what do I put here? Also can the

How to create decorator for lazy initialization of a property

喜你入骨 提交于 2019-12-21 00:23:13
问题 I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example: def SomeClass(object): @LazilyInitializedProperty def foo(self): print "Now initializing" return 5 >>> x = SomeClass() >>> x.foo Now initializing 5 >>> x.foo 5 My idea was to write a custom decorator for this. So i started, and this is how far I came: class LazilyInitializedProperty(object): def __init__(self,

python property decorator [duplicate]

泄露秘密 提交于 2019-12-20 11:36:30
问题 This question already has answers here : Closed 7 years ago . Possible Duplicate: Real world example about how to use property feature in python? I have a question about the decorator @property that I've seen in the following code. Could someone be kind enough to completely explain why someone would use the @property decorator? I know @property is equivalent to isActive = property(isActive) but what does the method property actually do to it's parameter? If I were to call the isActive method

python property decorator [duplicate]

孤者浪人 提交于 2019-12-20 11:36:17
问题 This question already has answers here : Closed 7 years ago . Possible Duplicate: Real world example about how to use property feature in python? I have a question about the decorator @property that I've seen in the following code. Could someone be kind enough to completely explain why someone would use the @property decorator? I know @property is equivalent to isActive = property(isActive) but what does the method property actually do to it's parameter? If I were to call the isActive method