这篇文章主要围绕在Python3.6中运行时根据Union类型检查变量和python以下程序的功能:判断输入的一个整数展开,旨在为您提供一份详细的参考资料。我们将全面介绍在Python3.6中运行时根
这篇文章主要围绕在Python 3.6中运行时根据Union类型检查变量和python以下程序的功能:判断输入的一个整数展开,旨在为您提供一份详细的参考资料。我们将全面介绍在Python 3.6中运行时根据Union类型检查变量的优缺点,解答python以下程序的功能:判断输入的一个整数的相关问题,同时也会为您带来Pyre —— Python 类型检查工具、python selenium-5根据unittest组织测试用例、python – 检查变量的多个值、python 函数参数类型检查的实用方法。
本文目录一览:- 在Python 3.6中运行时根据Union类型检查变量(python以下程序的功能:判断输入的一个整数)
- Pyre —— Python 类型检查工具
- python selenium-5根据unittest组织测试用例
- python – 检查变量的多个值
- python 函数参数类型检查
在Python 3.6中运行时根据Union类型检查变量(python以下程序的功能:判断输入的一个整数)
更新(2020年9月) :Python
3.9包含typing.get_type_hints
此用例的功能,请参阅https://docs.python.org/3.9/library/typing.html#typing.get_type_hints
我正在尝试编写一个使用Python 3.6类型提示的函数装饰器,以检查参数字典是否尊重类型提示,并且如果未出现带有问题清晰说明的错误,则将其用于HTTP
API。
问题是,当函数具有使用Union
类型的参数时,我无法在运行时根据其检查变量。
例如我有这个功能
from typing import Uniondef bark(myname: str, descr: Union[int, str], mynum: int = 3) -> str: return descr + myname * mynum
我可以:
isinstance(''Arnold'', bark.__annotations__[''myname''])
但不是:
isinstance(3, bark.__annotations__[''descr''])
因为Union
不能与isinstance
或一起使用issubclass
。
我找不到使用类型对象检查它的方法。我尝试自己执行检查,但是在REPL中bark.__annotations__[''descr'']
显示typing.Union[int,str]
时,如果不使用检查的丑陋技巧,我将无法在运行时访问类型列表bark.__annotations__[''descr''].__repr__()
。
是否有访问此信息的正确方法?还是故意在运行时不易于访问它?
答案1
小编典典您可以使用其中包含“可能内容”的__args__
属性:Union``tuple
>>> from typing import Union>>> x = Union[int, str]>>> x.__args__(int, str)>>> isinstance(3, x.__args__)True>>> isinstance(''a'', x.__args__)True
该__args__
参数未记录下来,因此可以认为是“与实现细节打交道”,但它似乎比解析更好repr
。
Pyre —— Python 类型检查工具
快速、可扩展和高性能的 Python 类型检查工具,适用于大型的 Python 3 代码库,旨在通过在终端或编辑器中以交互方式标记类型错误来帮助提高代码质量和开发速度
python selenium-5根据unittest组织测试用例
<img src="https://img2018.cnblogs.com/blog/1418970/201811/1418970-20181127115013408-189401019.png" width="300" /> * driver:浏览器driver存放地址 * testcase:测试用例目录 * report:测试结果保存目录 * runtest.py:执行文件 test_search1.py搜索selenium,test_search2搜索jenkins ```#python import unittest,sys from selenium import webdriver from time import sleep class TestBaidu(unittest.TestCase): def setUp(self): driver_path=''/''.join(sys.path[0].split(''/'')[:-2])+"/driver/chromedriver" self.driver=webdriver.Chrome(executable_path=driver_path) self.driver.implicitly_wait(30) self.base_url="http://www.baidu.com" def test(self): driver=self.driver driver.get(self.base_url+"/") driver.find_element_by_xpath("//input[@id=''kw'' and @s_ipt'']").clear() driver.find_element_by_xpath("//input[@id=''kw'' and @s_ipt'']").send_keys("selenium") driver.find_element_by_xpath("//input[@value=''百度一下'' and @id=''su'']").click() result_text = driver.find_element_by_xpath("//span[@nums_text'']").text assert "百度为您找到相关结果约" in result_text sleep(3) def tearDown(self): self.driver.quit() if __name__=="__main__": unittest.main() ``` runtest.py ```#python import unittest test_dir="./testcase/testsearch" discover=unittest.defaultTestLoader.discover(test_dir,pattern="test*.py") if __name__=="__main__": runner=unittest.TextTestRunner() runner.run(discover) ``` log.txt <img src="https://img2018.cnblogs.com/blog/1418970/201811/1418970-20181127115825840-144462564.png" width="400" />
python – 检查变量的多个值
original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): word = original.lower() first = str(word)[0] print first if str(first) == "a" or "e" or "i" or "u" or "o": print "vowel" else: print "consonant"
我想检查一个单词是否以元音或辅音开头.但是,这部分不起作用:如果str(first)==“a”或“e”或“i”或“u”或“o”
那么你如何检查第一个字母是“a”还是“e”或“i”或“u”还是“o”?
解决方法
if len(original) and original.isalpha(): word = original.lower() first = word[0] print first if first in ('a','e','i','o','u'): print "vowel" else: print "consonant"
你也做错了,如果你试图使用OR子句你必须使用这样但是它不是更好的pythonic方式:
if first =='a' or first =='e' or first =='i' or first =='o' or first =='u':
python 函数参数类型检查
在Python中,不知道函数参数类型是一个很正常的事情,特别是在一个大项目里。
我见过有些项目里,每一个函数体的前十几行都在检查参数类型,这实在是太麻烦了。而且一旦参数有改动,这部分也需要改动。
下面我们用装饰器来实现,函数参数的强制类型检查。
首先,这个装饰器,要接受类型参数,和指定函数参数的类型参数。也就是一个list
和一个dict
from functools import wraps
def typeassert(*type_args,**type_kwargs):
def decorate(func):
@wraps(func)
def wrapper(*args,**kwargs):
return func(*args,**kwargs)
return wrapper
return decorate
@wraps(func)
的作用请看另一篇
那么,接下来,在装饰器中,我们需要获取函数参数列表,并且要和类型参数表映射。
这要借助Python的一个标准库——inspect 这个库一般用于Python代码调试
from inspect import signature
from functools import wraps
def typeassert(*type_args,**type_kwargs):
def decorate(func):
sig = signature(func)
bound_types = sig.bind_partial(*type_args,**type_kwargs).arguments
@wraps(func)
def wrapper(*args,**kwargs)
return wrapper
return decorate
上面的代码中,我们使用inspect
中的signature
方法获取了func
的Signature
对象,然后使用bind_partial
方法创建了(*type_args,**type_kwargs)
到func
参数的映射(也就是一个字典)。
接下来就简单了,我们只需要再获取(*args,**kwargs)
的类型,使用 isinstance 函数进行比较就好。
from inspect import signature
from functools import wraps
def typeassert(*type_args,**kwargs):
bound_values = sig.bind(*args,**kwargs)
for name,value in bound_values.arguments.items():
if name in bound_types:
if not isinstance(value,bound_types[name]):
raise TypeError('Argument {} must be {}'.format(name,bound_types[name]))
return func(*args,**kwargs)
return wrapper
return decorate
运行如下代码
@typeassert(int,int)
def add(x,y):
return x+y
print(add("u",2))
能看到报错如下
Traceback (most recent call last):
File "c:\Users\Chen\Desktop\typeassert.py",line 32,in <module>
print(add("u",2))
File "c:\Users\Chen\Desktop\typeassert.py",line 22,in wrapper
'Argument {} must be {}'.format(name,bound_types[name])
TypeError: Argument x must be <class 'int'>
很贴心的提醒了我们哪一个参数应该是什么类型。你甚至可以自己改动这个装饰器,让它还能告诉你传进去了什么错误参数(特别是写爬虫的时候,参数很难掌握,一旦报错,还得重跑一遍才知道为什么。)
你也可以指定某一个参数的类型,譬如
@typeassert(int,z=str)
def display(x,y,z):
print(x,z)
这时你会发现,y的类型就像原生的Python函数一样,什么都行。而x必须是int
,z必须是str
。
关于在Python 3.6中运行时根据Union类型检查变量和python以下程序的功能:判断输入的一个整数的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Pyre —— Python 类型检查工具、python selenium-5根据unittest组织测试用例、python – 检查变量的多个值、python 函数参数类型检查等相关知识的信息别忘了在本站进行查找喔。
本文标签: