mozilla / metric-hub

Central hub for metric definitions that are considered the source of truth
https://mozilla.github.io/metric-hub
Mozilla Public License 2.0
13 stars 13 forks source link

define validators/converters for attrs classes #554

Open mikewilli opened 2 months ago

mikewilli commented 2 months ago

See the thread at the link below, but here's the main comment:

+1 to "let's do it later, not necessary for this PR"

As I understand it, default defines the default argument value while converter applies a function to the argument. Converters allow you to differentiate between the types of the parameters and the types of the attributes

So

class MyClass:
 x = attr.field(default = None, type = str | None)

will define a class with a constructor like:

MyClass.__init__(self, x: str | None = None):
 self.x = x # type will be str | None

If you add a converter:

class MyClass: 
 x = attr.field(default = None, type = str, converter=attr.converter.default_if_none("default"))

you'll get a class with a constructor like:

MyClass.__init__(self, x: str | None = None):
  self.x = x if x is not None else "default" # type will be str, no longer optional

I think it comes down to a question of 1) what parameters do we want callers to be able to pass to the constructor and 2) what type do we want the class attributes to be.

_Originally posted by @danielkberry in https://github.com/mozilla/metric-hub/pull/553#discussion_r1709823159_