Saravanan666/pypi-org huggingface dataset:
Package: pydantic-translations
pydantic-translationsTranslations for pydantic errors.LanguagesCurrently, we have translated pydantic v1.10.2 errors to the following languages:de: German. 87/87.es: Spanish. 87/87.fr: French. 87/87.it: Italian. 87/87.nl: Dutch. 87/87.ru: Russian. 82/87.Need more languages? Contributions are welcome!Installationpython3-mpipinstallpydantic-translationsUsageLet's say you have a pydantic modelUser:frompydanticimportBaseModelclassUser(BaseModel):age:intThe translations are managed by theTranslatorclass that is instantiated with the locale (language) you want the messages to be translated to:frompydantic_translationsimportTranslatortr=Translator('ru')You can use translator as a context manager to translate pydantic exceptions raised from the context:withtr:User.parse_obj({'age':'idk'})# ValidationError: 1 validation error for User# age#   значение должно быть целым числом (type=type_error.integer)Or use thetranslate_exceptionmethod to directly translate an exception instance:frompydanticimportValidationErrortry:User.parse_obj({'age':'idk'})exceptValidationErrorasexc:exc=tr.translate_exception(exc)raiseexcOr use thetranslate_errormethod to translate a specific error:try:User.parse_obj({'age':'idk'})exceptValidationErrorasexc:err=exc.errors()[0]err=tr.translate_error(err)print(err)# {'loc': ('age',), 'msg': 'значение должно быть целым числом', 'type': 'type_error.integer'}Custom translationsIf you have translated the errors to a new language, the best you can do is contribute it back here. If, for some (legal?) reason, you can't, you may pass into the Translated as a locale al10nlocale with your translations:froml10nimportLocaleslocales=Locales()locale=locales['ua']tr=Translator(locale)ContributorsThe original error messages provided by@samuelcolvinandpydantic contributors.The Russian translation is provided by@orsinium.The German, Spanish, French, Italian, and Dutch translations are provided byAndovartranslation agency.Minor corrections and improvements are provided bythe project contributors.
Package: pydantic-webargs
Pyndatic WebargsA library for parsing and validating http requests for flask web-framework using pydantic libraryFull documentationhereRequirementspython >= 3.7How to installpipinstallpydantic-webargsDependenciesflask
pydanticExamplefromflaskimportFlaskfrompydanticimportBaseModelfrompydantic_webargsimportwebargsapp=Flask(__name__)classQueryModel(BaseModel):name:strclassBodyModel(BaseModel):age:int@app.route("/get-request",methods=["GET"])@webargs(query=QueryModel)defexample_get_endpoint(**kwargs):response=kwargsreturnresponse@app.route("/post-request",methods=["POST"])@webargs(query=QueryModel,body=BodyModel)defexample_post_endpoint(**kwargs):print(kwargs)response=kwargsreturnresponseif__name__=="__main__":app.run(host="0.0.0.0",port=8000)
Package: pydantic_wrangler
pydantic-wranglerDescriptionpydantic-wrangler was born out of the necessity of representing data (originally serialized in YAML files) as python
objects not only capable of exhibiting complex business-logic behaviors, but also ensuring stringent data validation.As a result, it streamlines the process of parsing data from various serialization formats into Pydantic models, and if
necessary, re-serializing them back into any supported format. In essence, pydantic-wrangler serves as a comprehensive
tool for your data, facilitating a seamless journey from serialization to deserialization (and back, if you so wish).InstallationInstall it with pip:pipinstallpydantic-wrangleror poetry:poetryaddpydantic-wranglerFeaturesPydantic Integration: Converting serialized data into Python objects is the oldest trick in the book, but pydantic-wrangler
elevates this process by directly converting the data into Pydantic models, which brings the added advantage of robust
data validation. The models used in this process are defined by classes that inherit from either thePydanticWranglerBaseModelorPydanticWranglerRenderableModel. This not only provides flexibility in setting up
behaviors for your data, but also ensures data integrity through Pydantic's validation mechanisms.Multiple Formats Support: Currently, it supports loading serialized data from JSON, YAML, TOML  and INI streams/files.
While support for other formats is planned, the package is designed to be easily extensible. Adding your own loader function(s)
to support additional formats (and/or to include use-case specific business-logic) is as simple as defining them in a python module
(.py file) and creating an env var with name 'LOADERS_MODULE' containing the python dotted path to that module.
For more information, please refer to theCustom Loaderssection.Table of Contents [pending]UsageBase ModelsLoadersDumpersExtensibilityExample use-caseContributing
Package: pydantic-xml
pydantic-xmlis apydanticextension providing model fields xml binding
and xml serialization / deserialization.
It is closely integrated withpydanticwhich means it supports most of its features.Featurespydantic v1 / v2 supportflexable attributes, elements and text bindingpython collection types support (Dict,TypedDict,List,Set,Tuple, …)Uniontype supportpydanticgeneric modelssupportpydanticcomputed fieldssupportlxmlxml parser supportxml.etree.ElementTreestandard library xml parser supportWhat is not supported?dynamic model creationdataclassesGetting startedThe following model fields binding:classProduct(BaseXmlModel):status:Literal['running','development']=attr()# extracted from the 'status' attributelaunched:Optional[int]=attr(default=None)# extracted from the 'launched' attributetitle:str# extracted from the element textclassCompany(BaseXmlModel):trade_name:str=attr(name='trade-name')# extracted from the 'trade-name' attributewebsite:HttpUrl=element()# extracted from the 'website' element textproducts:List[Product]=element(tag='product',default=[])# extracted from the 'Company' element's childrendefines the XML document:<Companytrade-name="SpaceX"><website>https://www.spacex.com</website><productstatus="running"launched="2013">Severallaunchvehicles</product><productstatus="running"launched="2019">Starlink</product><productstatus="development">Starship</product></Company>Seedocumentationfor more details.
Package: pydantic-xml-converter
Pydantic XML ConverterAllows existing Pydantic models to be converted to/from XML with support for XML attributes.Installpip install pydantic-xml-extensionExamplesGenerating XML from an existing Pydantic modelfrompydanticimportfields,BaseModelfrompydantic_xmlimportPydanticXmlConverter,XmlAttributeclassCustomBaseModel(BaseModel):classConfig:allow_population_by_field_name=TrueclassExistingModel(CustomBaseModel):name:Annotated[str,fields.Field(alias="Name")]age:intmodel=ExistingModel(Name="test",age=12)converter=PydanticXmlConverter("Model")converter.set_xml_attribute("name",XmlAttribute(key="id",value="123"))converter.set_xml_attribute("age",XmlAttribute(key="custom",value="value"))print(converter.xml(model))>><?xmlversion="1.0"encoding="utf-8"?>>><Model><Nameid="123">test</Name><agecustom="value">12</age></Model>Creating an instance of an existing Pydantic model from XMLfrompydantic_xmlimportXmlBaseModel,XmlAttributeclassCustomBaseModel(BaseModel):classConfig:allow_population_by_field_name=TrueclassExistingModel(XmlBaseModel):name:Annotated[str,fields.Field(alias="Name")]age:intinput_xml='<Model><Name id="123">test</Name><age custom="value">12</age></Model>'converter=PydanticXmlConverter("Model")model=converter.parse_xml(input_xml,ExistingModel)print(model)>>Model(name="test",age=12)print(converter.generate_dict(model))>>{"Name":"test","age":12}print(converter.generate_dict(model,by_alias=False))>>{"name":"test","age":12}print(converter.generate_xml(model))>><?xmlversion="1.0"encoding="utf-8"?>>><Model><Nameid="123">test</Name><agecustom="value">12</age></Model>to view or access the saved attributes identified during parsing, you use theconverter.xml_attributesattribute.
Package: pydantic-xml-extension
Pydantic XML ConverterAllows existing Pydantic models to be converted to/from XML with support for XML attributes.Installpip install pydantic-xml-extensionExamplesGenerating XML from an existing Pydantic modelfrompydanticimportfields,BaseModelfrompydantic_xmlimportPydanticXmlConverter,XmlAttributeclassCustomBaseModel(BaseModel):classConfig:allow_population_by_field_name=TrueclassExistingModel(CustomBaseModel):name:Annotated[str,fields.Field(alias="Name")]age:intmodel=ExistingModel(Name="test",age=12)converter=PydanticXmlConverter("Model")converter.set_xml_attribute("name",XmlAttribute(key="id",value="123"))converter.set_xml_attribute("age",XmlAttribute(key="custom",value="value"))print(converter.xml(model))>><?xmlversion="1.0"encoding="utf-8"?>>><Model><Nameid="123">test</Name><agecustom="value">12</age></Model>Creating an instance of an existing Pydantic model from XMLfrompydantic_xmlimportXmlBaseModel,XmlAttributeclassCustomBaseModel(BaseModel):classConfig:allow_population_by_field_name=TrueclassExistingModel(XmlBaseModel):name:Annotated[str,fields.Field(alias="Name")]age:intinput_xml='<Model><Name id="123">test</Name><age custom="value">12</age></Model>'converter=PydanticXmlConverter("Model")model=converter.parse_xml(input_xml,ExistingModel)print(model)>>Model(name="test",age=12)print(converter.generate_dict(model))>>{"Name":"test","age":12}print(converter.generate_dict(model,by_alias=False))>>{"name":"test","age":12}print(converter.generate_xml(model))>><?xmlversion="1.0"encoding="utf-8"?>>><Model><Nameid="123">test</Name><agecustom="value">12</age></Model>to view or access the saved attributes identified during parsing, you use theconverter.xml_attributesattribute.
Package: pydantic-xmlmodel
PydanticXMLPydanticXML is a Python library that provides a way to convert Pydantic models to XML and vice versa. It is built on top of the Pydantic library and extends it with XML-specific functionality.FeaturesBased on Pydantic 2Convert Pydantic models to XML and vice versaSupport for XML attributes, elements, content, lists.Compatible with most Pydantic features (e.g. default values, aliases, validators,Fieldetc.)Very easy to use. Extends Pydantic's API with only a few methods.Has no dependencies other than PydanticFully tested (almost 100% coverage)Supports mypyInstallationYou can install PydanticXML with pip:pipinstallpydantic-xmlmodelUsageTo use PydanticXML, you need to import theBaseModelXMLclass from thepydanticxmlmodule:frompydantic_xmlmodelimportBaseModelXMLOr if your models is not based on BaseModelXML class you can use these functions:frompydantic_xmlmodelimportmodel_dump_xml,model_validate_xmlExamplesDefining a ModelYou can define a model by subclassingBaseModelXMLand defining attributes with type annotations:classAnimalCharacteristics(BaseModelXML):color:str="black"weight:int=10is_friendly:bool=TrueConverting a Model to XMLYou can convert a model to XML by calling themodel_dump_xml()method:classCat(BaseModelXML):animal_characteristics:AnimalCharacteristicsname:str="Kitty"cat=Cat(animal_characteristics=AnimalCharacteristics())print(cat.model_dump_xml())This will output:<?xml version="1.0" ?><Catname="Kitty"><AnimalCharacteristicscolor="black"weight="10"is_friendly="True"/></Cat>Converting XML to a ModelYou can convert XML to a model by calling themodel_validate_xml()method:xml='<?xml version="1.0" ?><Cat name="Kitty"><AnimalCharacteristics color="black" weight="10" is_friendly="True" /></Cat>'cat=Cat.model_validate_xml(xml)print(cat)This will output:xml_content=Noneanimal_characteristics=AnimalCharacteristics(xml_content=None,color='black',weight=10,is_friendly=True)name='Kitty'(Note that thexml_contentattribute is not part of the model. It is used to store the XML content, like this<element> xml_content <other_element /></element>)
Package: pydantic-yaml
Pydantic-YAMLPydantic-YAML adds YAML capabilities toPydantic,
which is anexcellentPython library for data validation and settings management.
If you aren't familiar with Pydantic, I would suggest you first check out theirdocs.Documentation on ReadTheDocs.orgBasic UsagefromenumimportEnumfrompydanticimportBaseModel,validatorfrompydantic_yamlimportparse_yaml_raw_as,to_yaml_strclassMyEnum(str,Enum):"""A custom enumeration that is YAML-safe."""a="a"b="b"classInnerModel(BaseModel):"""A normal pydantic model that can be used as an inner class."""fld:float=1.0classMyModel(BaseModel):"""Our custom Pydantic model."""x:int=1e:MyEnum=MyEnum.am:InnerModel=InnerModel()@validator("x")def_chk_x(cls,v:int)->int:# noqa"""You can add your normal pydantic validators, like this one."""assertv>0returnvm1=MyModel(x=2,e="b",m=InnerModel(fld=1.5))# This dumps to YAML and JSON respectivelyyml=to_yaml_str(m1)jsn=m1.json()# This parses YAML as the MyModel typem2=parse_yaml_raw_as(MyModel,yml)assertm1==m2# JSON is also valid YAML, so this works toom3=parse_yaml_raw_as(MyModel,jsn)assertm1==m3With Pydantic v2, you can also dump dataclasses:frompydanticimportRootModelfrompydantic.dataclassesimportdataclassfrompydantic.versionimportVERSIONasPYDANTIC_VERSIONfrompydantic_yamlimportto_yaml_strassertPYDANTIC_VERSION>="2"@dataclassclassYourType:foo:str="bar"obj=YourType(foo="wuz")assertto_yaml_str(RootModel[YourType](obj))=='foo: wuz\n'ConfigurationCurrently we use the JSON dumping of Pydantic to perform most of the magic.This uses theConfiginner class,as in Pydantic:classMyModel(BaseModel):# ...classConfig:# You can override these fields, which affect JSON and YAML:json_dumps=my_custom_dumperjson_loads=lambdax:MyModel()# As well as other Pydantic configuration:allow_mutation=FalseYou can control some YAML-specfic options via the keyword options:to_yaml_str(model,indent=4)# Makes it widerto_yaml_str(model,map_indent=9,sequence_indent=7)# ... you monster.You can additionally pass your ownYAMLinstance:fromruamel.yamlimportYAMLmy_writer=YAML(typ="safe")my_writer.default_flow_style=Trueto_yaml_file("foo.yaml",model,custom_yaml_writer=my_writer)A separate configuration for YAML specifically will be added later, likely in v2.Breaking Changes forpydantic-yamlV1The API forpydantic-yamlversion 1.0.0 has been greatly simplified!Mixin ClassThis functionality has currently been removed!YamlModelandYamlModelMixinbase classes are no longer needed.
The plan is to re-add it before v1 fully releases,
to allow the.yaml()or.parse_*()methods.
However, this will be availble only forpydantic<2.Versioned ModelsThis functionality has been removed, as it's questionably useful for most users.
There is anexample in the docsthat's available.
Package: pydantic-yaml-parser
pydantic-yaml-parserInstallpipinstallpydantic_yaml_parserBackground & Usage1. Loading YAML into Pydantic modelsTo load YAML into a Pydantic model, you have to first convert the YAML
string to a dict. For example, given the below yaml file:yaml_string="""setting_1: Hellosetting_2:- kind: namesublist:- first- second"""You might define a Pydantic model to represent it like this:frompydanticimportBaseModelfromtypingimportListclassSetting2(BaseModel):kind:strsublist:ListclassTest(BaseModel):setting_1:strsetting_2:List[Setting2]You can load the yaml file into a dict, and into the Pydantic model like
so usingpyyaml:importyamlyml_dict=yaml.safe_load(yaml_string)# use `parse_obj` to load a dictTest.parse_obj(yml_dict)Test(setting_1='Hello', setting_2=[Setting2(kind='name', sublist=['first', 'second'])])2. The Pydantic validation error messageHowever, let’s say there is an error in your yaml file such that you
accidentally setsublisttofalse, instead of settingsublisttolisttype, you will get an error message that looks like this:yaml_string="""setting_1: oksetting_2:- kind: namesublist: false"""yaml_dict_error=yaml.safe_load(yaml_string)Test.parse_obj(yaml_dict_error)ValidationError: 1 validation error for Test
setting_2 -> 0 -> sublist
  value is not a valid list (type=type_error.list)This error message is a bit confusing, especially for those with no
prior experience with pydantic!3. Human readable error messages withpydantic_yaml_parserWhen you usepydantic_yaml_parseryou get an error message that is
much clearer:frompydantic_yaml_parser.yamlimportYamlModelclassTest(YamlModel):setting_1:strsetting_2:List[Setting2]Test.from_dict(yaml_dict_error)ValueError: Configuration error(s) for YAML:
 - value is not a valid list: `sublist` for element 0 in the list for `setting_2`Further ReadingFor more examples of error validation seethese
docs.
Package: pydantic-zarr
pydantic-zarrPydanticmodels forZarr.⚠️ Disclaimer ⚠️This project is under a lot of flux -- I want to addzarr version 3support to this project, but thereference python implementationdoesn't support version 3 yet. Also, the key ideas in this repo may change in the process of being formalized over inthis specification(currently just a draft). As the ecosystem evolves Iwillbe breaking things (and versioning the project accordingly), so be advised!Installationpip install -U pydantic-zarrHelpSee thedocumentationfor detailed information about this project.Exampleimportzarrfrompydantic_zarrimportGroupSpecgroup=zarr.group(path='foo')array=zarr.create(store=group.store,path='foo/bar',shape=10,dtype='uint8')array.attrs.put({'metadata':'hello'})# this is a pydantic modelspec=GroupSpec.from_zarr(group)print(spec.model_dump())"""{'zarr_version': 2,'attributes': {},'members': {'bar': {'zarr_version': 2,'attributes': {'metadata': 'hello'},'shape': (10,),'chunks': (10,),'dtype': '|u1','fill_value': 0,'order': 'C','filters': None,'dimension_separator': '.','compressor': {'id': 'blosc','cname': 'lz4','clevel': 5,'shuffle': 1,'blocksize': 0,},}},}"""
Package: pydantify
PydantifyAprototypeCLI tool to transform YANG models into Pydantic datastructures that can be initialized with config values and serialized into RESTCONF payloads.Check out the documentation https://pydantify.github.io/pydantify/For usersInstallationPrerequisites:Python 3.10pipInstalling from PYPI:pipinstallpydantifyInstalling from local folder:pipinstall.UsageExample:pydantify -i ./models_dir -o ./output_dir -t interfaces/ethernet model.yangTransforms the/interfaces/ethernetnode and its children (located inmodel.yang) into a Python script located in./output_dir. Imports of definitions found in./models_dirare included if relevant to the specified model and node.Command syntax:pydantify [-h] [-v] [-V] [-S] [-i INPUT_DIR] [-o OUTPUT_DIR] [-t TRIM_PATH] input_file

positional arguments:
  input_file            The YANG file containing the entrypoint to the model to evaluate.

options:
  -h, --help            show this help message and exit
  -v, --verbose         Enables debug output
  -V, --include-verification
                        Adds validation code, as well as the relevant YANG files, to the output model.
  -S, --standalone      Generated output model has no dependency on Pydantify.
                        All required code is copied into the output model.
  -i INPUT_DIR, --input-dir INPUT_DIR, --path INPUT_DIR
                        The directory that contains the YANG input model.
                        Defaults to the input file's folder.
  -o OUTPUT_DIR, --output-dir OUTPUT_DIR
                        The directory that should be used to store the output model. Defaults to "$CWD/out".
  -t TRIM_PATH, --trim-path TRIM_PATH
                        Get only the specified branch of the whole tree.

NOTE: All unknown arguments will be passed to Pyang as-is and without guarantees.For developersRequirements:Visual Studio CodePython 3.10PDM package managerInstructions:Note: instructions with the same indentation are alternatives to eachother.Installdependencies through pdm (pdm installin project root)into the local__pypackages__folderto run your project as a python modulelocally (python -m pydantify)in a docker container (seeDockerfile)to be accessed by your IDE for intellisense (see.vscode/settings.json)to be accessed by your debug launch configuration (see.vscode/launch.json)project through pip (see guide for users)Buildthrough pdm (pdm build)into the localdistfolderto be published on pypithrough twine (twine upload dist/*)Links relevant to projectPydanticsourcedocumentationExplanationsYang concepts (yangson)yang-python training examplesYang modelsYangModels/yangPyangpyangThanksDejan Jovicic and Dominic Walther, who laid the foundations of pydantify
Package: pydantigraph
pydantigraphORM data models, schemas, and vocabularies for pyoxigraphORM-like read/write with pyoxigraphRead - just model fieldsRead - model fields + all triples with matching subjectLazy read - read connected entities when accessedWriteUpdateDeleteCrawl - get triples n-steps out from current object leaves with filteringNamespaces for using schemaCode generation from existing schemaFields and type annotations for declaring termsFields are properly checked by MyPy using the first type parameterLists <-> blank node collectionsPydantic validationJSON-SchemaRDF serialization with rdflibIRI (not URL) validatorOnly fields that map onto RDF literals allowedSee Alsohttps://pypi.org/project/rdflib-orm/
Package: pydanttention
pydanttentionTransformer model attention in Pydantic.Adapted from the source by Theia Vogel (MIT licensed, included here asvogel_manual_transformer.py):I made a transformer by hand (no training!)(2023)In turn using model ops frompicoGPT(MIT license)MotivationRewriting AI model source code as Pydantic data models is an interesting exercise. I'd note the following benefits.All operations can be subclassed from an arbitraryOperationmodel (see.models.ops.base),
i.e. they all expect their first argument to be a numpy arrayx. This naturally allows you to
factor your code around a category of 'operations'.Since all functions get turned into a class (a Pydantic data model with type-annotated fields for
input state rather than funcdef kw/args), and classes are conventionally named inPascalCasewhereas functions
(like all other Python variables) are conventionally named insnake_case, you can easily observe from case alone
where significant operations are called, as well as where the data model is referenced (byself.{field}) making
these 2 types of data access distinct from the intermediate variables. This gives a better sense
at a glance of data flow through your program.State can be configured at runtime but also given defaults at import time through use of fields in
the data model. The original source code hardcoded values in the config as module globals
(similarly to using class variables), it was not possible to configure component parts at runtime.
This was appropriate to author an expository demo, but made it difficult to approach as a reader
wishing to modify and experiment (likewise code is easier to test if easier to configure at runtime).Clear and consolidated declarations of input data (i.e. not scattered across many sites of declaration)
without losing the ability to decompose into structured components. The original code used primitive types
(lists of dictionaries) for the attention blocks, which became model field defaults in a self-contained module (see.models.config).
Since Pydantic allows you to load ("validate") typed data models from these primitive types, we
could supply the original dictionary primitive toAttentionBlock.model_validateand it'd still work
(but doing so is actually more verbose than just constructing the model class directly).
Package: pyDAOE
PyDAOE: Design and Analysis of ExperimentsA collection of utilities for the analysis of experiments.Based on the bookDesign and Analysis of Experimentsby Douglas C. Montgomery,
which is covered by theDesign of Experiments Specializationon Coursera, taught by Prof. Montgomery himself.Note that you can freely attend all the lectures as an auditor, and each "week" of lecture covers
exactly one chapter of the book (12 in total, divised into 4 courses).You can also browse a summary of the DoE concepts asnotes of the STAT 503 course at Penn State University.After downloading and installing the package as:git clone https://github.com/danieleongari/pyDAOE.git
cd pyDAOE
pip install -e .you can find the examples and exercises inspired from the book in thetestsfolder.
The reference version of the book uses imperial units, and specifically the 9th edition of the book,
which is also used as a reference in the Coursera specialization.