BrendanSimon
BrendanSimon

Reputation: 711

How to specify an __init__ argument that is not a class attribute

With attrs, how can I specify an init argument that is not a class attribute.

e.g. a CRC8 object might be passed some bytes or bytearray in the constructor, but I don't want to store that input, just calculate the CRC and store the result.

Is this pattern an example where using a class method is appropriate (as described in this link)?

http://www.attrs.org/en/stable/init.html#initialization

Upvotes: 2

Views: 796

Answers (1)

hynek
hynek

Reputation: 4126

What you want here is a classmethod factory:

@attr.s
class CRC8:
    checksum = attr.ib()

    @classmethod
    def from_bytes(cls, bytes):
        # compute your CRC
        # checksum = ...
        return cls(checksum)

That allows you to do proper checks and balances.

In this case I'd wonder if a function wouldn’t do? Similarly to the standard library's binascii.crc32().

Upvotes: 3

Related Questions