You’re not allowed to use P.kwargs
in an annotation without P.args
, so it will be hard for us to provide a precise signature for this function at typeshed in the way you suggest above. (FWIW, I agree that this is an awesome new feature, and don’t think that the fact that it’s difficult to have accurate type annotations for it is in any way an argument against adding the feature.)
I hope it didn’t sound like I was suggesting that!
Just curious, but the dependency of one type variable on another is okay?
def replace[T: SupportsReplace[P], **P]
I wasn’t sure if that would work.
It didn’t – I was just clarifying that it also was not my opinion either
Er, yeah, that’s illegal too, good point
I proposed adding SupportsReplace
protocol to typing
here: Incorrect rendering of `__replace__` method in `copy` docs: consider adding `typing.SupportsReplace`? · Issue #109961 · python/cpython · GitHub
**kwargs
would have to be Any
(for now at least).
copy.replace
is great, however I keep writing:
def __replace__(self, **kwargs: Any) -> Self: # Allow replacements.
new = copy.deepcopy(self)
for key, value in kwargs.items():
setattr(new, key, value)
return new
Why not add something like this to object
?
- It only works for mutable objects.
- You used
deepcopy()
, but in many case you don’t need to make copies of all attributes (they can even be uncopiable) or you only need to make a level 1 copy of an attribute. This cannot be generalized.deepcopy()
is too rought tool. replace()
usually does not allow setting arbitrary attributes.- Constructor can have side effect, and you want this side effect happens with values specified as the keyword arguments of
replace()
rather than with original values.
@storchaka Yes to all your points, but that doesn’t prevent a useful default from being provided. The documentation could list all your points as reasons to override.
You could just use dataclasses if you want useful defaults for most things.
@NeilGirdhar Yes, I use dataclasses a lot and pydantic, but there are still times when a normal class is a good choice.