mentalisttraceur / python-macaddress

BSD Zero Clause License
19 stars 5 forks source link

Add `.from_str`, `.from_bytes`, and `.from_int` `classmethod` constructors? #21

Closed mentalisttraceur closed 2 years ago

mentalisttraceur commented 2 years ago

Verdict: no, unless someone brings a particularly compelling reason probably, if people start asking for it.

Rationale: users can easily compose type-constraining functions on top of a type-flexible constructor, like this:

import macaddress

# When hardware address class is known:
def eui48_from_str(string: str) -> macaddress.EUI48:
    if not isinstance(string, str):
        raise TypeError(f"not a string: {string!r}")
    return macaddress.EUI48(string)

# When hardware address class is dynamic:
from typing import Type, TypeVar

HWAddressType = TypeVar('HWAddress', bound=macaddress.HWAddress)

def from_str(cls: HWAddressType, string: str) -> HWAddressType:
    if not isinstance(string, str):
        raise TypeError(f"not a string: {string!r}")
    return cls(string)

However, Python is a batteries-included language, and I could imagine wanting these batteries in this library. So if someone finds themselves wanting it, I might be pretty easily swayed, especially by seeing an example use-case where this is nicer to have out-of-the-box.

mentalisttraceur commented 2 years ago

Users can similarly define subclasses which add the above functions as @classmethod-decorated methods, or do the isinstance check before calling super().__init__(...) - whether subclassing like that is better or worse than external helper functions is a separate matter, but it's also possible.