如何用python的装饰器定义一个像C++一样的强类型函数
def fun(a:int, b=1, *c, d, e=2, **f) -> str:
pass
这里主要是说几点与python2中不同的点。





# _*_ coding: utf-8
import functools
import inspect
from itertools import chain def typesafe(func):
"""
Verify that the function is called with the right arguments types and that
it returns a value of the right type, accordings to its annotations.
"""
spec = inspect.getfullargspec(func)
annotations = spec.annotations for name, annotation in annotations.items():
if not isinstance(annotation, type):
raise TypeError("The annotation for '%s' is not a type." % name) error = "Wrong type for %s: expected %s, got %s."
# Deal with default parameters
defaults = spec.defaults or ()
defaults_zip = zip(spec.args[-len(defaults):], defaults)
kwonlydefaults = spec.kwonlydefaults or {}
for name, value in chain(defaults_zip, kwonlydefaults.items()):
if name in annotations and not isinstance(value, annotations[name]):
raise TypeError(error % ('default value of %s' % name,
annotations[name].__name__,
type(value).__name__)) @functools.wraps(func)
def wrapper(*args, **kwargs):
# Populate a dictionary of explicit arguments passed positionally
explicit_args = dict(zip(spec.args, args))
keyword_args = kwargs.copy()
# Add all explicit arguments passed by keyword
for name in chain(spec.args, spec.kwonlyargs):
if name in kwargs:
explicit_args[name] = keyword_args.pop(name) # Deal with explict arguments
for name, arg in explicit_args.items():
if name in annotations and not isinstance(arg, annotations[name]):
raise TypeError(error % (name,
annotations[name].__name__,
type(arg).__name__)) # Deal with variable positional arguments
if spec.varargs and spec.varargs in annotations:
annotation = annotations[spec.varargs]
for i, arg in enumerate(args[len(spec.args):]):
if not isinstance(arg, annotation):
raise TypeError(error % ('variable argument %s' % (i+1),
annotation.__name__,
type(arg).__name__)) # Deal with variable keyword argument
if spec.varkw and spec.varkw in annotations:
annotation = annotations[spec.varkw]
for name, arg in keyword_args.items():
if not isinstance(arg, annotation):
raise TypeError(error % (name,
annotation.__name__,
type(arg).__name__)) # Deal with return value
r = func(*args, **kwargs)
if 'return' in annotations and not isinstance(r, annotations['return']):
raise TypeError(error % ('the return value',
annotations['return'].__name__,
type(r).__name__))
return r return wrapper
对于上面的代码:
# _*_ coding: utf-8
import functools
import inspect
from itertools import chain def precessArg(value, annotation):
try:
return annotation(value)
except ValueError as e:
print('value:', value)
raise TypeError('Expected: %s, got: %s' % (annotation.__name__,
type(value).__name__)) def typesafe(func):
"""
Verify that the function is called with the right arguments types and that
it returns a value of the right type, accordings to its annotations.
"""
spec = inspect.getfullargspec(func)
annotations = spec.annotations for name, annotation in annotations.items():
if not isinstance(annotation, type):
raise TypeError("The annotation for '%s' is not a type." % name) error = "Wrong type for %s: expected %s, got %s."
# Deal with default parameters
defaults = spec.defaults and list(spec.defaults) or []
defaults_zip = zip(spec.args[-len(defaults):], defaults)
i = 0
for name, value in defaults_zip:
if name in annotations:
defaults[i] = precessArg(value, annotations[name])
i += 1
func.__defaults__ = tuple(defaults) kwonlydefaults = spec.kwonlydefaults or {}
for name, value in kwonlydefaults.items():
if name in annotations:
kwonlydefaults[name] = precessArg(value, annotations[name])
func.__kwdefaults__ = kwonlydefaults @functools.wraps(func)
def wrapper(*args, **kwargs):
keyword_args = kwargs.copy()
new_args = args and list(args) or []
new_kwargs = kwargs.copy()
# Deal with explicit argument passed positionally
i = 0
for name, arg in zip(spec.args, args):
if name in annotations:
new_args[i] = precessArg(arg, annotations[name])
i += 1 # Add all explicit arguments passed by keyword
for name in chain(spec.args, spec.kwonlyargs):
poped_name = None
if name in kwargs:
poped_name = keyword_args.pop(name)
if poped_name is not None and name in annotations:
new_kwargs[name] = precessArg(poped_name, annotations[name]) # Deal with variable positional arguments
if spec.varargs and spec.varargs in annotations:
annotation = annotations[spec.varargs]
for i, arg in enumerate(args[len(spec.args):]):
new_args[i] = precessArg(arg, annotation) # Deal with variable keyword argument
if spec.varkw and spec.varkw in annotations:
annotation = annotations[spec.varkw]
for name, arg in keyword_args.items():
new_kwargs[name] = precessArg(arg, annotation) # Deal with return value
r = func(*new_args, **new_kwargs)
if 'return' in annotations:
r = precessArg(r, annotations['return'])
return r return wrapper if __name__ == '__main__':
print("Begin test.")
print("Test case 1:")
try:
@typesafe
def testfun1(a:'This is a para.'):
print('called OK!')
except TypeError as e:
print("TypeError: %s" % e) print("Test case 2:")
try:
@typesafe
def testfun2(a:int,b:str = 'defaule'):
print('called OK!')
testfun2('str',1)
except TypeError as e:
print("TypeError: %s" % e) print("test case 3:")
try:
@typesafe
def testfun3(a:int, b:int = 'str'):
print('called OK')
except TypeError as e:
print('TypeError: %s' % e) print("Test case 4:")
try:
@typesafe
def testfun4(a:int = '', b:int = 1.2):
print('called OK.')
print(a, b)
testfun4()
except TypeError as e:
print('TypeError: %s' % e) @typesafe
def testfun5(a:int, b, c:int = 1, d = 2, *e:int, f:int, g, h:int = 3, i = 4, **j:int) -> str :
print('called OK.')
print(a, b, c, d, e, f, g, h, i, j)
return 'OK' print("Test case 5:")
try:
testfun5(1.2, 'whatever', f = 2.3, g = 'whatever')
except TypeError as e:
print('TypeError: %s' % e) print("Test case 6:")
try:
testfun5(1.2, 'whatever', 2.2, 3.2, 'e1', f = '', g = 'whatever')
except TypeError as e:
print('TypeError: %s' % e) print("Test case 7:")
try:
testfun5(1.2, 'whatever', 2.2, 3.2, 12, f = '', g = 'whatever')
except TypeError as e:
print('TypeError: %s' % e) print("Test case 8:")
try:
testfun5(1.2, 'whatever', 2.2, 3.2, 12, f = '', g = 'whatever', key1 = 'key1')
except TypeError as e:
print('TypeError: %s' % e) print("Test case 9:")
try:
testfun5(1.2, 'whatever', 2.2, 3.2, 12, f = '', g = 'whatever', key1 = '')
except TypeError as e:
print('TypeError: %s' % e) print('Test case 10:')
@typesafe
def testfun10(a) -> int:
print('called OK.')
return 'OK'
try:
testfun10(1)
except TypeError as e:
print('TypeError: %s' % e)
如何用python的装饰器定义一个像C++一样的强类型函数的更多相关文章
- $python用装饰器实现一个计时器
直接上代码: import time from functools import wraps # 定义装饰器 def fn_timer(function): @wraps(function) def ...
- python基础—装饰器
python基础-装饰器 定义:一个函数,可以接受一个函数作为参数,对该函数进行一些包装,不改变函数的本身. def foo(): return 123 a=foo(); b=foo; print(a ...
- 【Python】装饰器理解
以下文章转载自:点这里 关于装饰器相关的帖子记录在这里: 廖雪峰, thy专栏, stackflow Python的函数是对象 简单的例子: def shout(word="yes" ...
- Python之装饰器、迭代器和生成器
在学习python的时候,三大“名器”对没有其他语言编程经验的人来说,应该算是一个小难点,本次博客就博主自己对装饰器.迭代器和生成器理解进行解释. 为什么要使用装饰器 什么是装饰器?“装饰”从字面意思 ...
- 关于python的装饰器(初解)
在python中,装饰器(decorator)是一个主要的函数,在工作中,有了装饰器简直如虎添翼,许多公司面试题也会考装饰器,而装饰器的意思又很难让人理解. python中,装饰器是一个帮函数动态增加 ...
- 如何写一个Python万能装饰器,既可以装饰有参数的方法,也可以装饰无参数方法,或者有无返回值都可以装饰
Python中的装饰器,可以有参数,可以有返回值,那么如何能让这个装饰器既可以装饰没有参数没有返回值的方法,又可以装饰有返回值或者有参数的方法呢?有一种万能装饰器,代码如下: def decorate ...
- 第7.27节 Python案例详解: @property装饰器定义属性访问方法getter、setter、deleter
上节详细介绍了利用@property装饰器定义属性的语法,本节通过具体案例来进一步说明. 一. 案例说明 本节的案例是定义Rectangle(长方形)类,为了说明问题,除构造函数外,其他方法都只 ...
- 第7.26节 Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解
第7.26节 Python中的@property装饰器定义属性访问方法getter.setter.deleter 详解 一. 引言 Python中的装饰器在前面接触过,老猿还没有深入展开介绍装饰 ...
- Python使用property函数和使用@property装饰器定义属性访问方法的异同点分析
Python使用property函数和使用@property装饰器都能定义属性的get.set及delete的访问方法,他们的相同点主要如下三点: 1.定义这些方法后,代码中对相关属性的访问实际上都会 ...
随机推荐
- 用Spark查询HBase中的表数据
java代码如下: package db.query; import org.apache.commons.logging.Log; import org.apache.commons.logging ...
- Objective-C:三种文件导入的方式比较
三种文件导入的方式比较: 类的前项声明@class.import.include: 1.采用@class 类名的方式,它会告诉编译器有这么一个类,目前不需要知道它内部的实例变量和方法是如何定义 ...
- 浅析Linux线程调度
在Linux中,线程是由进程来实现,线程就是轻量级进程( lightweight process ),因此在Linux中,线程的调度是按照进程的调度方式来进行调度的,也就是说线程是调度单元.Linux ...
- 动态图片 Movie android-gif-drawable GifView
Movie 类 文档位置:/sdk/docs/reference/android/graphics/Movie.html 官方对这个类连一句介绍都没有,并且所有的方法也没有一行注释,可见多么不受重视! ...
- IOS Xib使用——Xib表示局部界面
Xib文件是一个轻量级的用来描述局部界面的文件,在之前的文章讲解了为控制器添加Xib文件,本节主要讲解一下通过xib文件表示局部界面. <一> 创建Xib文件 Xib文件创建的时候是选择U ...
- IOS 设置圆角用户头像
在App中有一个常见的功能,从系统相册或者打开照相机得到一张图片,然后作为用户的头像.从相册中选取的图片明明都是矩形的图片,但是展示到界面上却变成圆形图片,这个神奇的效果是如何实现的呢? 请大家跟着下 ...
- 解决百度ueditor支持iframe框架页面的视频播放问题
新下载的ueditor 增加了xss 安全过虑,把iframe过滤了,导致发表的文章包含的视频播放功能被限制了. 说明:新版本ueditor要修改 xss过滤白名单 修改配置文件ueditor.con ...
- Android -- SlidingMenu
实现原理 在一个Activity的布局中需要有两部分,一个是菜单(menu)的布局,一个是内容(content)的布局.两个布局横向排列,菜单布局在左,内容布局在右.初始化的时候将菜单布局向左偏移,以 ...
- java核心技术36讲
https://time.geekbang.org/column/intro/82?utm_source=website&utm_medium=infoq&utm_campaign=8 ...
- 在Foreda8上试安装Apchehttpd-2.4.6.tar.gz
下文是我边试边做的记录,不保证内容的完整性和正确性. 由于我的Apsire机器是最简安装Foreda8,所以需要安装httpd,熟悉一遍也是很好的嘛. 我从网上搜罗并下载了apchehttpd-2.4 ...