@@ -143,7 +143,7 @@ class PatchOp(Message, Generic[T]):
143143 - Using PatchOp without a type parameter raises TypeError
144144 """
145145
146- def __new__ (cls , * args , ** kwargs ):
146+ def __new__ (cls , * args : Any , ** kwargs : Any ):
147147 """Create new PatchOp instance with type parameter validation.
148148
149149 Only handles the case of direct instantiation without type parameter (PatchOp()).
@@ -165,9 +165,23 @@ def __new__(cls, *args, **kwargs):
165165 def __class_getitem__ (cls , item ):
166166 """Validate type parameter when creating parameterized type.
167167
168- Ensures the type parameter is a concrete Resource subclass (not Resource itself).
169- Rejects invalid types (str, int, etc.) and Union types.
168+ Ensures the type parameter is a concrete Resource subclass (not Resource itself)
169+ or a TypeVar bound to Resource. Rejects invalid types (str, int, etc.) and Union types.
170170 """
171+ # Allow TypeVar as type parameter
172+ if isinstance (item , TypeVar ):
173+ # Check if TypeVar is bound to Resource or its subclass
174+ if item .__bound__ is not None and (
175+ item .__bound__ is Resource
176+ or (isclass (item .__bound__ ) and issubclass (item .__bound__ , Resource ))
177+ ):
178+ return super ().__class_getitem__ (item )
179+ else :
180+ raise TypeError (
181+ f"PatchOp TypeVar must be bound to Resource or its subclass, got { item } . "
182+ "Example: T = TypeVar('T', bound=Resource)"
183+ )
184+
171185 # Check if type parameter is a concrete Resource subclass (not Resource itself)
172186 if item is Resource :
173187 raise TypeError (
@@ -176,7 +190,7 @@ def __class_getitem__(cls, item):
176190 )
177191 if not (isclass (item ) and issubclass (item , Resource ) and item is not Resource ):
178192 raise TypeError (
179- f"PatchOp type parameter must be a concrete Resource subclass, got { item } . "
193+ f"PatchOp type parameter must be a concrete Resource subclass or TypeVar , got { item } . "
180194 "Use PatchOp[User], PatchOp[Group], etc."
181195 )
182196
0 commit comments