Last active
September 8, 2017 19:49
-
-
Save andr1an/d051f54fc33ee142a9c3d7ab5d0be407 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""Пример декоратора. | |
Декоратор - функция, которая принимает функцию, как аргумент, и подменяет | |
её имплементацию другой функцией. | |
Например, @cached заворачивает свою функцию-аргумент в функцию try_cache, | |
которая перед возвращением значения будет класть его в кеш для ускорения | |
повторного вызова. | |
Для функции подмены необходимо использовать декоратор functools.wraps, | |
чтобы она не заменила декорированную ей функцию | |
(см. https://stackoverflow.com/a/309000). | |
""" | |
from functools import wraps | |
def cached(function): | |
"""Caches results.""" | |
cache = {} | |
@wraps(function) | |
def try_cache(*args): | |
if args not in cache: | |
cache[args] = function(*args) | |
print 'Cache:', cache | |
return cache[args] | |
return try_cache | |
@cached | |
def is_div(number, quotinent): | |
return number % quotinent == 0 | |
def main(): | |
"""Main function for the application.""" | |
print is_div(16, 2) | |
print is_div(2356, 3) | |
print is_div(2356, 3) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment