Created
June 22, 2024 09:39
-
-
Save cthoyt/89ea8eb7cc008efbcc89a944c43af215 to your computer and use it in GitHub Desktop.
Use the Bioregistry for Pydantic (v2) validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bioregistry | |
from pydantic.functional_validators import AfterValidator | |
def validate_local_identifier(prefix: str) -> AfterValidator: | |
"""Make a validator function based on a Bioregistry prefix. | |
Example usage: | |
.. code-block:: python | |
from typing import Annotated | |
from pydantic import BaseModel | |
class Scholar(BaseModel): | |
orcid: Annotated[str, validate_local_identifier("orcid")] | |
Scholar(orcid="0000-0003-4423-4370") # works | |
Scholar(orcid="nope") # fails to pass regular expression check | |
""" | |
resource = bioregistry.get_resource(prefix) | |
if not resource: | |
raise ValueError | |
def _validate(identifier: str) -> str: | |
if not resource.is_valid_identifier(identifier): | |
raise ValueError | |
return identifier | |
return AfterValidator(_validate) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment