Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(Python)函数装饰器,用于将剧作家页面对象传递给包装函数_Python_Python 3.x_Decorator_Wrapper_Python Decorators - Fatal编程技术网

(Python)函数装饰器,用于将剧作家页面对象传递给包装函数

(Python)函数装饰器,用于将剧作家页面对象传递给包装函数,python,python-3.x,decorator,wrapper,python-decorators,Python,Python 3.x,Decorator,Wrapper,Python Decorators,目标:我正在尝试创建一个函数装饰器,它将一个剧作家页面(剧作家.sync\u api.\u generated.Page)对象传递给包装函数 问题:对于大多数函数调用,我能够返回函数调用返回的值。然而,由于剧作家需要调用browser.close()调用,所以我不能简单地返回Page对象。我不确定问题出在(1)我定义的函数装饰器,还是(2)我对函数装饰器的使用 我尝试在pytestfixture之后为我的装饰器建模。使用pytest,我会这样做: @pytest.fixture(scope=“m

目标:我正在尝试创建一个函数装饰器,它将一个剧作家
页面
剧作家.sync\u api.\u generated.Page)
对象传递给包装函数

问题:对于大多数函数调用,我能够返回函数调用返回的值。然而,由于剧作家需要调用
browser.close()
调用,所以我不能简单地返回
Page
对象。我不确定问题出在(1)我定义的函数装饰器,还是(2)我对函数装饰器的使用

我尝试在
pytest
fixture之后为我的装饰器建模。使用
pytest
,我会这样做:

@pytest.fixture(scope=“module”)
def剧作家_page():
将sync_playright()作为剧本:
browser=play.chromium.launch()
页面=浏览器。新建页面()
产量页
browser.close()
然后

def open_谷歌(剧作家页面):
剧作家_page.goto(“https://google.com")

功能解码器

>>来自playright.sync\u api导入sync\u playright
>>>def剧作家页面(func):
def包装(*args,**kwargs):
将sync_playright()作为剧本:
browser=play.chromium.launch()
页面=浏览器。新建页面()
产量页
browser.close()
返回包装器
尝试1

>@剧作家\u页面
def open_google():
第页转到“https://google.com")
>>>打开谷歌()
尝试2

>@剧作家\u页面
def open_google():
第页=下一页(第页)
第页转到“https://google.com")
>>>打开谷歌()

我应该调用
func
并传递
页面
对象,而不是尝试生成
页面
对象,比如
pytest
装置

>>来自playright.sync\u api导入sync\u playright
>>>def剧作家页面(func):
def包装器():
将sync_playright()作为剧本:
browser=play.chromium.launch()
页面=浏览器。新建页面()
结果=函数(第页)
browser.close()
返回结果
返回包装器
>>>@playstright\u page
def open_google(第页):
第页转到“https://google.com")

我想补充一点,如果函数的返回值可能很重要,装饰程序可能应该执行类似
results=func(page)
的操作,然后在
browser.close()之后
返回结果