14
14
15
15
import inspect
16
16
from typing import Any , Callable , Dict , List , Optional
17
- from weakref import WeakKeyDictionary
18
17
19
18
from playwright ._impl ._api_types import Error
20
19
20
+ INSTANCE_ATTR = "_pw_api_instance"
21
+
21
22
22
23
class ImplWrapper :
23
24
def __init__ (self , impl_obj : Any ) -> None :
@@ -27,7 +28,6 @@ def __init__(self, impl_obj: Any) -> None:
27
28
class ImplToApiMapping :
28
29
def __init__ (self ) -> None :
29
30
self ._mapping : Dict [type , type ] = {}
30
- self ._instances : WeakKeyDictionary [Any , Any ] = WeakKeyDictionary ()
31
31
32
32
def register (self , impl_class : type , api_class : type ) -> None :
33
33
self ._mapping [impl_class ] = api_class
@@ -39,13 +39,15 @@ def from_maybe_impl(self, obj: Any) -> Any:
39
39
return {name : self .from_maybe_impl (value ) for name , value in obj .items ()}
40
40
if isinstance (obj , list ):
41
41
return [self .from_maybe_impl (item ) for item in obj ]
42
- if obj not in self ._instances :
43
- api_class = self ._mapping .get (type (obj ))
44
- if not api_class :
45
- return obj
46
- api_instance = api_class (obj )
47
- self ._instances [obj ] = api_instance
48
- return self ._instances [obj ]
42
+ api_class = self ._mapping .get (type (obj ))
43
+ if api_class :
44
+ api_instance = getattr (obj , INSTANCE_ATTR , None )
45
+ if not api_instance :
46
+ api_instance = api_class (obj )
47
+ setattr (obj , INSTANCE_ATTR , api_instance )
48
+ return api_instance
49
+ else :
50
+ return obj
49
51
50
52
def from_impl (self , obj : Any ) -> Any :
51
53
assert obj
@@ -77,14 +79,14 @@ def to_impl(self, obj: Any) -> Any:
77
79
raise Error ("Maximum argument depth exceeded" )
78
80
79
81
def wrap_handler (self , handler : Callable [..., None ]) -> Callable [..., None ]:
80
- if handler in self ._instances :
81
- return self ._instances [handler ]
82
-
83
- def wrapper (* args : Any ) -> Any :
82
+ def wrapper_func (* args : Any ) -> Any :
84
83
arg_count = len (inspect .signature (handler ).parameters )
85
84
return handler (
86
85
* list (map (lambda a : self .from_maybe_impl (a ), args ))[:arg_count ]
87
86
)
88
87
89
- self ._instances [handler ] = wrapper
88
+ wrapper = getattr (handler , INSTANCE_ATTR , None )
89
+ if not wrapper :
90
+ wrapper = wrapper_func
91
+ setattr (handler , INSTANCE_ATTR , wrapper )
90
92
return wrapper
0 commit comments