Python function Heat more (at development time)

Source: Internet
Author: User

Python function Hot More (run-time update)


    1. Implement function run-time modification (development environment!!!) , not on-line heat more!!! )
    2. Support for the co-function (tornado)


from /path/to/realtimefunc import realtimefunc@coroutine@realtimefuncdef test():    # function body

When it comes to heat, it's easy to associate it with the heat of the product on the line. There are front ends, there are also backstage. However, it is mentioned here that the heat is more in the background of Python development.

Development also need heat more??
Development also has human rights ah, what! No? Then you have to toss a.

The start-up of a backend service typically requires considerable preparation, resulting in slower startup. Development of the server is generally not comparable to the line, the start speed is more noticeable.

When you come into contact with a Python backend project as a little white, you may encounter two situations when you need to do development on it.

1. 去理解一个功能, 数据存储的结构在理解占很大一部分,对 python 这种动态数据结构, 通过代码, 很难清晰看到一个功能(相关dict,list, set等)定义的数据结构, 或者一些全局变量的具体结构以及内容。一些固定的也许可以直接通过 db 查看数据结构, 但一些内存的中的数据,就难以顾及了。2. 实现一个功能写了一大段代码, 这大段代码中隐藏 bug 团伙,python 是运行时检测,也就是代码运行到具体语句才会报错, 这样报错之后的 bug 君依然得以隐藏,如果服务启动需要5分钟,bug 团伙规模达到 6 个以上,小半个小时就没了。而这些 bug 可能只是简单 key error, 真是想想都要崩溃。

Remark :

很多web框架有自启动, 是通过检测项目文件的 mtime , 然后替换掉当前的服务进程,比如 tornado 就是用一个定时器定时检测项目文件, 实现 autostart。但这种重启的是整个服务,所以费时并不会减少。

It's natural to think that it would be nice if you could change the code at any time without restarting the entire service.

Achieve the goal:
Implements an adorner, the decorated function arbitrarily modifies, does not need to restart the service, the new request takes effect immediately.

Implementation ideas:
When called by the decorator function, the function code is obtained from the. py file using Inspect.getsource, and the function is redefined and named by exec, allowing the modification of the function code to take effect in the next call. Latest Code Address Realtimefunc

#-*-coding:iso-8859-1-*-import sysimport linecacheimport refrom Inspect import getsource, getfile# A decorator is used To update a function at runtime.    Decoratorname = ' realtimefunc ' suffix = ' _runtime ' PY3 = Sys.version_info >= (3,) if Py3:basestring_type = Strelse: Basestring_type = basestring # noqadef _exec_in (code, GLOB, Loc=none): # Type: (Any, dict[str, any], optional[mapping [STR, any]]) -and any if Isinstance (code, Basestring_type): # EXEC (String) inherits the caller's future imports;        Compile # The string first to prevent. Code = Compile (code, ' <string> ', ' exec ', dont_inherit=true) exec (code, GLOB, loc) def _handle_real_time_func_code ( Func, split= ' \ n '): Code = GetSource (func) i_indent = 0 I_decorator = 0 code_lines = code.split (split) func_ Pat = Re.compile (R ' ^\s*def\s+ ' +func.__name__) for I, line in enumerate (code_lines): If "@" +decoratorname on line : I_decorator = i if FUNC_PAT.MATCH (line): I_indent = Line.index ("def") code_lines[i] = Code_lines[i].replace (Func.func_name,    C_name+suffix, 1) Break # RM Realtimefunc Decorator Code_lines.pop (i_decorator) # code indentation Code_lines = [line[i_indent:] for line in Code_lines] code = split.join (code_lines) return codedef Realtimefunc (func  ): Def wrapper (*args, **kwargs): filename = GetFile (func) # Inspect use Linecache to does file cache, so do Checkcache first Linecache.checkcache (filename) code_str = _handle_real_time_func_code (func) _exec_i        N (code_str,func.__globals__, func.__globals__) # A return expected when are work, if not yield instead. return Func.__globals__[func.__name__+suffix] (*args, **kwargs) return wrapper

Implementing the Development runtime modification functions makes it easy to view and modify the data associated with the decorated function, as well as to construct simple test data and perform simple branch testing.
For a covariant function, for example, if you use a lower version of Tornado (for example, 4.1), change the return to yield, where the position is commented in the code
Inspect useful to linecache cache, in obtaining the function source code needs to check the cache

This article applies small white, big God detour, small white amuse oneself!!!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: