未加星标

Python Decorators Demonstration

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二04 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

(Sponsors) Get started learning python with DataCamp's free Intro to Python tutorial . Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

When improving your Python programming language, you must come across the Decorators that are one of the elegant features heavily used in modern libraries and frameworks. To encapsulate a lot of implementation details and leave out a simple interface, the decorators are very good tools to serve the purpose.

Let us take an example of simple login decorator that makes sure the user is logged in before any edition in the posts. This ensures redirecting to the login page by setting the right parameters to redirect back to the same page after successful registration. To avail this function, all you need to do is just put @login_required before the function.

@login_required def edit_post(post_id): ...

Decorators are very easy to use and work with, but writing decorators are even confusing for experienced Python developers. Pop in the article for more explanation on how Python decorators work in simple steps.

Functions

Functions are also called first-class objects in Python. The functions are values just like numbers, lists, and strings as seen in the following example.

>>> def foo(): ... return 1 ... >>> >>> foo() 1 >>>

Functions also have their own namespace which looks first to find variable names when it encounters them in the function body. To investigate the difference between local and global scope, let’s write a simple function.

>>> >>> a_string = "This is a global variable" >>> >>> def foo(): ... print(locals()) ... >>> >>> print(globals()) {..., 'a_string': 'This is a global variable'} >>> >>> foo() # 2 {} >>> Function Scope as a Variable

In Python scope rule, variable creation always creates a new local variable but accessing the variable looks in the local scope by searching all the enclosing scopes to find a match. This does not mean that we cannot access global variables inside our functions. To modify the function foo to print out global variable we would expect to work as:

>>> >>> a_string = "This is a global variable" >>> >>> def foo(): ... print(a_string) #1 ... >>> >>> foo() This is a global variable >>> Variable Lifetime

Not only variables live inside a namespace but they also have lifetimes which is important to note. Consider the example to not just scope rules that cause a problem but it also has to do with how function calls and implemented in Python and other languages.

>>> def foo(): ... x = 1 ... >>> foo() >>> >>> print(x) # 1 Traceback (most recent call last): ... NameError: name 'x' is not defined >>> Nested functions

The creation of nested functions is allowed in Python which means we can declare functions inside of the functions and all the scoping and lifetime rules still get applied normally.

>>> >>> def outer(): ... x = 1 ... def inner(): ... print(x) # 1 ... inner() # 2 ... >>> outer() 1 >>> Decorators

A closure that takes a function as a parameter and returns a replacement function is called a decorator. Let us look at an example to work with useful decorators.

>>> >>> def outer(some_func): ... def inner(): ... print("before some_func") ... ret = some_func() # 1 ... return ret + 1 ... return inner ... >>> def foo(): ... return 1 ... >>> decorated = outer(foo) # 2 >>> >>> decorated() before some_func 2 >>>

The decorated variable is a decorated version of foo. In fact, we might want to replace foo with the decorated version altogether without learning any new syntax simply by reassigning the variable that contains our function:

>>> >>> foo = outer(foo) >>> >>> foo # doctest: +ELLIPSIS <function outer.<locals>.inner at 0x...> >>>

Now, to trace the function calls we have a beautiful decorator. The decorators can be used to manipulate any programming language using Python language. This has powerful implications so you should now understand how they work and when they are useful.

Author Bio

Kibo Hutchinson is a Technology analyst at Tatvasoft UK which is a software development company in London. She strongly believes that knowledge is meant to be shared and in this post she is sharing her insights on Python.

Other Tutorials (Sponsors)

This site generously supported by DataCamp . DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

代码区博客精选文章
分页:12
转载请注明
本文标题:Python Decorators Demonstration
本站链接:https://www.codesec.net/view/628292.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(57)