pydantic / pydantic-extra-types

Extra Pydantic types.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add 6 character only `as_hex` e.g. `Color("red").as_hex(format="long") == #ff0000`

DJRHails opened this issue · comments

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

Description

Currently I use a custom function for converting Pydantic Color to hex, to remove the unexpected return value of #f00 when I expect #ff0000 instead.

def as_hex(color: Color) -> str:
    rgb_hex = ''.join(f'{v:02x}' for v in data.signature.brand_color.as_rgb_tuple())
    return f"#{rgb_hex}"

I propose (and happy to contribute), an optional parameter e.g. format="long" to allow non-compressed hex values.

Affected Components

Thanks @DJRHails for this feature request.

As you may know, We are working on Pydantic V2, and Color type is deprecated in Pydantic V2.

We moved this and some other extra types to a separate package pydantic-extra-types.

I am moving this issue there.

Appreciated @hramezani!

PR welcome. 👍

The signature should be def as_hex(self, format: Literal['short', 'long'] = 'short') for backwards compatibility.

Great I'll get a PR in tonight