python-decorators

Python Decorator Self-firing

纵然是瞬间 提交于 2019-12-20 07:12:20
问题 I am fairly new to Python and have been learning about decorators. After messing around with Flask, I am trying to write some code that simulates their route handler/decorators, just to understand how decorators (with arguments) work. In the code below, the route decorator seems to call itself once the script runs. My question is, how is it possible that app.route() gets called when i run this script, and what is really happening here? Notice i don't call my index() function anywhere directly

A function composition operator in Python

丶灬走出姿态 提交于 2019-12-20 05:25:51
问题 In this question I asked about a function composition operator in Python. @Philip Tzou offered the following code, which does the job. import functools class Composable: def __init__(self, func): self.func = func functools.update_wrapper(self, func) def __matmul__(self, other): return lambda *args, **kw: self.func(other.func(*args, **kw)) def __call__(self, *args, **kw): return self.func(*args, **kw) I added the following functions. def __mul__(self, other): return lambda *args, **kw: self

Decorating Python's builtin print() function

…衆ロ難τιáo~ 提交于 2019-12-19 19:40:50
问题 As we know in Python 3 print() is a function, is it possible to create a decorated version of it wrapped under json.dumps(indent=4) for ex. Calling print(mydict) should produce the same result as print(json.dumps(mydict, indent=4)) 回答1: You don't need a decorator per se to do that. Just define a new function and call it print : import builtins def print(*args, **kwargs): builtins.print(json.dumps(*args, **kwargs, indent=4)) You can use the builtins module as shown to access the original print

Is it possible to numpy.vectorize an instance method?

别来无恙 提交于 2019-12-19 14:05:15
问题 I've found that the numpy.vectorize allows one to convert 'ordinary' functions which expect a single number as input to a function which can also convert a list of inputs into a list in which the function has been mapped to each input. For example, the following tests pass: import numpy as np import pytest @np.vectorize def f(x): if x == 0: return 1 else: return 2 def test_1(): assert list(f([0, 1, 2])) == [1, 2, 2] def test_2(): assert f(0) == 1 if __name__ == "__main__": pytest.main([__file

Python decorators count function call

北慕城南 提交于 2019-12-19 08:13:30
问题 I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code: def call_counter(func): def helper(x): helper.calls += 1 return func(x) helper.calls = 0 return helper @call_counter def succ(x): return x + 1 if __name__ == '__main__': print(succ.calls) for i in range(10): print(succ(i)) print(succ.calls) What I don't get

setter method of property decorator not being called

試著忘記壹切 提交于 2019-12-19 06:03:25
问题 I am trying to use a property method to set the status of a class instance, with the following class definition: class Result: def __init__(self,x=None,y=None): self.x = float(x) self.y = float(y) self._visible = False self._status = "You can't see me" @property def visible(self): return self._visible @visible.setter def visible(self,value): if value == True: if self.x is not None and self.y is not None: self._visible = True self._status = "You can see me!" else: self._visible = False raise

setter method of property decorator not being called

天大地大妈咪最大 提交于 2019-12-19 06:00:29
问题 I am trying to use a property method to set the status of a class instance, with the following class definition: class Result: def __init__(self,x=None,y=None): self.x = float(x) self.y = float(y) self._visible = False self._status = "You can't see me" @property def visible(self): return self._visible @visible.setter def visible(self,value): if value == True: if self.x is not None and self.y is not None: self._visible = True self._status = "You can see me!" else: self._visible = False raise

Decorating a class to monitor attribute changes

丶灬走出姿态 提交于 2019-12-18 13:48:30
问题 I want to have classes that automatically send notifications to subscribers whenever one of their attributes change. So if I would write this code: @ChangeMonitor class ChangingClass(object): def __init__(self, x): self.x = x changer = ChangingClass(5) print("Going to change x.") changer.x = 6 print("Going to not change x.") changer.x = 6 print("End of program") The output would be: Going to change x Old x = 5, new x = 6 Going to not change x. End of program. My question is how to implement

Flask: Decorator to verify JSON and JSON Schema

自古美人都是妖i 提交于 2019-12-18 10:26:28
问题 I have a flask application with calls expecting JSON payload. Before each call is processed, I have a 2-step error checking process: Assert that the payload is a valid JSON Assert that the JSON payload complies with a specific schema Which is implemented in the following fashion: @app.route('/activate', methods=['POST']) def activate(): request_id = request.__hash__() # Assert that the payload is a valid JSON try: input = request.json except BadRequest, e: msg = "payload must be a valid json"

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

旧时模样 提交于 2019-12-17 21:38:27
问题 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? 回答1: 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__