Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

this is not the method chaining idiom you're looking for #12280

Open
cagney opened this issue Jan 13, 2025 · 3 comments
Open

this is not the method chaining idiom you're looking for #12280

cagney opened this issue Jan 13, 2025 · 3 comments

Comments

@cagney
Copy link

cagney commented Jan 13, 2025

ref Method Chining

The documentation for Creating a self-signed certificate has the example:

cert = x509.CertificateBuilder().subject_name(
    subject
).issuer_name(
    issuer
).public_key(
    key.public_key()
).serial_nuber(
    x509.random_serial_number()
...
).sign(key, hashes.SHA256())

which sure looks a lot like method chaining where each call returns self. When I read the documentation, for the individual functions, such as CertificateBuilder.subnect_name()

    Sets the subject’s distinguished name.
    Parameters:
        name – The [Name](https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Name) that describes the subject.

the documentation states that the method will set the name, again consistent with method chaining.

However, when I try to invoke this code using the method chaining's alternative form:

cert_builder = x509.CertificateBuilder()
cert_builder.subject_name(subject)

things don't work. It turns out that, rather than setting the existing builder, each of the above calls return a new instance of the builder. Which means that:

cert_builder = x509.CertificateBuilder()
cert_builder = cert_builder.subject_name(subject)
...

must be used.

The only hint I've seen of this is in CertificateBuilder reference documentation which uses the above; but without explanation.

@alex
Copy link
Member

alex commented Jan 13, 2025

Yes, we should change the documentation to more clearly indicate this: "Returns a new builder with the certificate's subject to this value.", and with :return: annotations.

Would you be interested in submitting a pull request for this?

@cagney
Copy link
Author

cagney commented Jan 13, 2025

I think it would be more useful to see the code made consistent with the idiom.

@alex
Copy link
Member

alex commented Jan 13, 2025

We think immutability is a better design pattern across the board, so we don't have an interest in changing it.

However, even if we did, it'd be wildly backwards incompatible and thus breaking of many downstream users, so it'd be difficult the justify.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants