{"id":13160,"date":"2023-06-13T10:00:00","date_gmt":"2023-06-13T01:00:00","guid":{"rendered":"https:\/\/www.gigas-jp.com\/appnews\/?p=13160"},"modified":"2023-06-13T12:56:25","modified_gmt":"2023-06-13T03:56:25","slug":"python-decorators","status":"publish","type":"post","link":"https:\/\/www.gigas-jp.com\/appnews\/archives\/13160","title":{"rendered":"Python Decorators"},"content":{"rendered":"\n<p>Today, I would like to share about Python decorators which simplify the code with powerful function enhancements. Python decorators are a powerful feature that allows developers to modify or enhance the behavior of functions or classes without directly modifying their source code. Decorators provide a clean and concise way to add functionality to existing code, making it easier to manage and reuse.<\/p>\n\n\n\n<p>What are Decorators?<\/p>\n\n\n\n<p>Decorators are functions that take another function as input and extend its functionality. They wrap the original function with additional code, allowing for actions like logging, authentication, and more, to be applied to multiple functions in a consistent and reusable manner.<\/p>\n\n\n\n<p>Example 1: Logging Decorator<\/p>\n\n\n\n<p>Let&#8217;s consider a simple example of a logging decorator. The decorator adds logging statements before and after the execution of a function:<\/p>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def logger(func):\n    def wrapper(*args, **kwargs):\n        print(f\"Calling function: {func.__name__}\")\n        result = func(*args, **kwargs)\n        print(f\"Function {func.__name__} executed\")\n        return result\n    return wrapper\n\n@logger\ndef add(a, b):\n    return a + b\n\n# Using the decorated function\nresult = add(3, 5)\nprint(result)  # Output: 8<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p>In this example, the `logger` function is a decorator that takes the function `add` as input. It defines an inner function `wrapper`, which performs the logging operations and calls the original function. The decorator then returns the `wrapper` function, which replaces the original `add` function.<\/p>\n\n\n\n<p>Example 2: Authorization Decorator<\/p>\n\n\n\n<p>Decorators can also be used for implementing authorization checks. Let&#8217;s see an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def authenticate(func):\n    def wrapper(*args, **kwargs):\n        if check_authentication():\n            return func(*args, **kwargs)\n        else:\n            raise Exception(\"Unauthorized access!\")\n    return wrapper\n\n@authenticate\ndef sensitive_operation():\n    # Perform sensitive operation here\n    pass\n\n# Using the decorated function\nsensitive_operation()<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p>In this example, the `authenticate` decorator checks if the user is authenticated before executing the `sensitive_operation` function. If the user is authenticated, the function is executed; otherwise, an exception is raised.<\/p>\n\n\n\n<p>Conclusion<\/p>\n\n\n\n<p>Python decorators provide a powerful and flexible way to modify the behavior of functions or classes without modifying their original code. They enable code reuse, separation of concerns, and cleaner code organization. By using decorators, developers can enhance their programs with additional features, such as logging, authentication, caching, and more, with minimal effort and maximum efficiency.<\/p>\n\n\n\n<p>This is all for now. Hope you enjoy that.<\/p>\n\n\n\n<p>By Asahi<\/p>\n<div class='wp_social_bookmarking_light'>\n            <div class=\"wsbl_google_plus_one\"><g:plusone size=\"medium\" annotation=\"none\" href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/13160\" ><\/g:plusone><\/div>\n            <div class=\"wsbl_hatena_button\"><a href=\"\/\/b.hatena.ne.jp\/entry\/https:\/\/www.gigas-jp.com\/appnews\/archives\/13160\" class=\"hatena-bookmark-button\" data-hatena-bookmark-title=\"Python Decorators\" data-hatena-bookmark-layout=\"standard\" title=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\"> <img src=\"\/\/b.hatena.ne.jp\/images\/entry-button\/button-only@2x.png\" alt=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\" width=\"20\" height=\"20\" style=\"border: none;\" \/><\/a><script type=\"text\/javascript\" src=\"\/\/b.hatena.ne.jp\/js\/bookmark_button.js\" charset=\"utf-8\" async=\"async\"><\/script><\/div>\n            <div class=\"wsbl_twitter\"><a href=\"https:\/\/twitter.com\/share\" class=\"twitter-share-button\" data-url=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/13160\" data-text=\"Python Decorators\" data-via=\"GIGASJAPAN_APPS\" data-lang=\"ja\">Tweet<\/a><\/div>\n            <div class=\"wsbl_facebook_like\"><div id=\"fb-root\"><\/div><fb:like href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/13160\" layout=\"button_count\" action=\"like\" width=\"100\" share=\"false\" show_faces=\"false\" ><\/fb:like><\/div>\n            <div class=\"wsbl_facebook_send\"><div id=\"fb-root\"><\/div><fb:send href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/13160\" colorscheme=\"light\" ><\/fb:send><\/div>\n    <\/div>\n<br class='wp_social_bookmarking_light_clear' \/>\n","protected":false},"excerpt":{"rendered":"<p>Today, I would like to share about Python decorators which simplify the code with powerful function enhancemen [&hellip;]<\/p>\n","protected":false},"author":20,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[100],"tags":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/13160"}],"collection":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/users\/20"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/comments?post=13160"}],"version-history":[{"count":1,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/13160\/revisions"}],"predecessor-version":[{"id":13161,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/13160\/revisions\/13161"}],"wp:attachment":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/media?parent=13160"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/categories?post=13160"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/tags?post=13160"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}