Make UniqueConstraint name required in signature

A UniqueConstraint requires a name argument, but is declared optional (=None) in its signature. If name is omitted a ValueError is raised. This is not as obvious as it could be by explicitly requiring the argument as part of the signature.

Background

Commit 3aa545281 introduced support for functional unique constraints, addressing ticket 30016. The new signature of UniqueConstraint adds an argument for expressions and makes fields optional, accepting either fields or expressions. It also makes name optional, while still enforcing it it by raising an exception if None.

Some reasoning is mentioned in a comment on the PR. Stating the now outdated change was “backward incompatible”. Unfortunately, we can’t see the patch the comment refers to.

But in the context of the merged diff, I don’t understand why name was defined as optional. It was required before and is still technically required.

Proposal

I’d like to see the signature of UniqueConstraint change, to explicitly define name as required. This allows developers to know that name is required from within their IDE. Would this change break backward compatibility today?

Thanks to Kavyansh on Discord for originally bringing this up, and @ulgens for helping dig into it.

1 Like

I’m +1 for changing it back to required, and I think we can make the change without any issues or deprecation period, since we’d basically be swapping ValueError for TypeError.

I don’t think there was a well-understood reason for the change at the time. The closest theory I have is that the authors thought that *expressions, fields=() would look nicer, as it places the two field arguments next to each other, and that following arguments, starting with name, would need defaults, though they actually don’t.

1 Like