Saravanan666/pypi-org huggingface dataset:
Package: pydantic-mongo-document
Pydantic Mongo Documentpydantic_mongo_documentis a Python library that provides a base class for creating MongoDB documents using Pydantic models.InstallationInstall the package usingpiporpoetry.Using pippipinstallpydantic_mongo_documentUsing poetrypoetryaddpydantic_mongo_documentUsage
To use pydantic_mongo_document, you need to create a Pydantic model that represents your MongoDB document and inherit from the MongoDocument class provided by the library. Here's an example:frompydantic_mongo_documentimportDocumentclassUser(Document):__collection__="users"__database__="production"name:stremail:strIn this example, we define a User Pydantic Document model with two fields (name and email) andspecifies the MongoDB collection name (users) and database name (production) using the__collection__and__database__class attributes.frompydantic_mongo_documentimportDocument# Set the MongoDB URIDocument.set_mongo_uri("mongodb://localhost:27017")classUser(Document):__collection__="users"__database__="production"name:stremail:strasyncdefcreate_user():user=User(name="John",email="john@example.com")awaituser.insert()user=awaitUser.one(add_query={"name":"John"})print(user)# User(id=ObjectId("64fc59cf6410868c9a40644b"), name="John", email="john@example")In this example, we created new User in database. We then used theUser.onemethod to retrieve the user from the database.ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMIT
Package: pydantic-mql
Pydantic MQLThis library can parse and evaluate conditions using pydantic. The usage is similar to the MongoDB Query Language.
But instead of filtering documents within a database collection you can use the library to filter arbitrary application
data in memory.Example UsageParsingfrompydantic_mqlimportConditiontest_json='{"operator": "$eq", "field": "label", "value": "lab"}'condition=Condition.model_validate_json(test_json)print(condition)Serializingfrompydantic_mqlimportConditioncondition=Condition(operator='$and',conditions=[Condition(operator='$eq',field='label',value='lab'),Condition(operator='$lte',field='rating',value=80)])print(condition.model_dump())Condition Evaltest_data={'rating':60,'label':'lab'}result=condition.eval(test_data)print(result)
Package: pydantic_numpy
pydantic-numpyPackage that integrates NumPy Arrays into Pydantic!pydantic_numpy.typingprovides many typings such asNpNDArrayFp64,Np3DArrayFp64(float64 that must be 3D)! Works with bothpydantic.BaseModelandpydantic.dataclassNumpyModel(derived frompydantic.BaseModel) make it possible to dump and loadnp.ndarraywithin model fields alongside other fields that are not instances ofnp.ndarray!See thetest.helper.groupsto see types that are defined explicitly. Define your own NumPy types withpydantic_numpy.np_array_pydantic_annotated_typing.UsageFor more examples seetest_ndarray.pyimportnumpyasnpfrompydanticimportBaseModelimportpydantic_numpy.typingaspndfrompydantic_numpyimportnp_array_pydantic_annotated_typingfrompydantic_numpy.modelimportNumpyModel,MultiArrayNumpyFileclassMyBaseModelDerivedModel(BaseModel):any_array_dtype_and_dimension:pnd.NpNDArray# Must be numpy float32 as dtypek:np_array_pydantic_annotated_typing(data_type=np.float32)shorthand_for_k:pnd.NpNDArrayFp32must_be_1d_np_array:np_array_pydantic_annotated_typing(dimensions=1)classMyDemoNumpyModel(NumpyModel):k:np_array_pydantic_annotated_typing(data_type=np.float32)# Instantiate from arraycfg=MyDemoModel(k=[1,2])# Instantiate from numpy filecfg=MyDemoModel(k="path_to/array.npy")# Instantiate from npz file with keycfg=MyDemoModel(k=MultiArrayNumpyFile(path="path_to/array.npz",key="k"))cfg.k# np.ndarray[np.float32]cfg.dump("path_to_dump_dir","object_id")cfg.load("path_to_dump_dir","object_id")NumpyModel.loadrequires the original model:MyNumpyModel.load(<path>)Usemodel_agnostic_loadwhen you have several models that may be the correct model:frompydantic_numpy.modelimportmodel_agnostic_loadcfg.dump("path_to_dump_dir","object_id")equals_cfg=model_agnostic_load("path_to_dump_dir","object_id",models=[MyNumpyModel,MyDemoModel])Installpipinstallpydantic-numpyConsiderationsYou can install fromcheind'srepository if you want Python3.8support, but this version only supports Pydantic V1 and will not work with V2.Licensing noticeAs of version3.0.0the license has moved over to BSD-4. The versions prior are under the MIT license.HistoryThe original idea originates fromthis discussion, and forked fromcheind'srepository.
Package: pydantic-ome-ngff
pydantic-ome-ngffaboutPydantic models for OME-NGFF metadata. Versions 0.4 and the latest (v0.5-dev) are currently supported.supported metadata models:multiscales(spec)axes(spec)coordinateTransformations(spec)plate(spec)well(spec)imageLabel(spec)omeroandbioformats2raware not currently supported, but contributions adding
support for those models would be welcome.Support for container-level validation (i.e., checking that multiscale or coordinate
transformation metadata is compatible with a hierarchical array / group layout) is being added incrementally.installationpipinstallpydantic-ome-ngffdevelopmentclone this repoinstallpoetryrunpoetry install --with devto get dev dependenciesrunpre-commit installto installpre-commit hooks
Package: pydantic-openai
pydantic-openaiPydantic models for OpenAI's API. These make it easier to construct requests and parse responses, as well as set up API-compatible servers.Making requests is explicitly out of scope.This is mostly translated fromsashabaranov/go-openai, by ChatGPT. I welcome translating the rest over, I just don't really use the other API's.UsageSee the package onPyPI.pipinstallpydantic-openaifrompydantic_openaiimportChatCompletionRequest
Package: pydantic-openapi-helper
pydantic-openapi-helperA small module to add additional post-processing to the OpenAPI schemas that are generated
by Pydantic.This module is designed to work with Ladybug Tools schema libraries such ashoneybee-schema,dragonfly-schemaandqueenbeebut might be also helpful for
other projects.The most important feature of the library is to generate an OpenAPI schema to use
polymorphism. It adds referenced values to subclasses using allOf field as explained in
this post:https://swagger.io/docs/specification/data-models/inheritance-and-polymorphismWe are not intending to support the development for make this library work universally
but you are more than welcome to fork and make your own version of the library.installationpython3 -m pip install pydantic-openapi-helper
Package: pydantic-prompter
Pydantic PrompterPydantic Prompter is a lightweight utility designed to facilitate the construction of prompts using YAML and generate Pydantic objects as outputs.Documentationhttps://helmanofer.github.io/pydantic-prompterInstallationTo install Pydantic Prompter, use the following command:pipinstallpydantic-prompterSetupBefore using Pydantic Prompter, ensure that you set your OpenAI API key as an environment variable:exportOPENAI_API_KEY=<youropenaitoken>Basic usageBegin by defining your output model using Pydantic:frompydanticimportBaseModel,FieldfromtypingimportListclassRecommendedEntry(BaseModel):id:strname:strreason:str=Field(description="Why this entry fits the query",default="")classRecommendationResults(BaseModel):title:strentries:List[RecommendedEntry]Next, create a Prompter function, which is defined as a YAML string with Jinja2 templating or simple string formatting:frompydantic_prompterimportPrompter@Prompter(llm="openai",jinja=True,model_name="gpt-3.5-turbo-16k")defrank_recommendation(entries,query)->RecommendationResults:"""- system: You are a movie ranking expert- user: >Which of the following JSON entries fit best to the query.order by best fit descendingBase your answer ONLY on the given JSON entries,if you are not sure, or there are no entries- user: >The JSON entries:{{ entries }}- user: "query: {{ query }}""""Execute your function as follows:my_entries="[{\"text\":\"Description: Four everyday suburban guys come together as a ...."print(rank_recommendation(entries=my_entries,query="Romantic comedy"))For debugging purposes, inspect your prompt with:print(rank_recommendation.build_string(entries=my_entries,query="Romantic comedy"))For additional details, refer to theDocumentation
Package: pydantic-property
Added a field_property which gives property like functionality to pydantic models.Note:Due to the way pydantic is written the field_property will be slow and inefficient.
Pydantic heavily uses and modifies the __dict__ attribute while overloading __setattr__.
Additionally, Pydantic’s metaclass modifies the class __dict__ before class creation removing all
property objects from the class definition.
These changes prevent property objects and normal descriptors from working.To work around this setting the field_property value must run the normal pydantic __setattr__,
run the object __setattr__ to call the property setter, and must update the __dict__ with all field_property values.
The Pydantic model __dict__ is only updated on __setattr__ and does not dynamically retrieve values.Simple ExamplefrompydanticimportPrivateAttrfrompydantic_propertyimportPropertyModel,field_propertyclassProps(PropertyModel):x:int=field_property('_x',default=0)# getter is created with '_x'@x.setterdefx(self,value):self._x=value# Note: matches field_property('_x')y:int=field_property('_y',default=0)# Need to define '_y' for __private_attribute__@y.getterdefy(self)->int:returngetattr(self,'_y',0)@y.setterdefy(self,value):ifisinstance(value,float):self._x=int((value%1)*10)# Must update all field_property with __dict__ for _x to be seenself._y=int(value)# Does not have a __private_attribute__ so '_z' will fail. we hack this later for testing@field_property(default=0)defz(self):returngetattr(self,'_z',0)@z.setterdefz(self,value):self._z=value# Have to add private attribute to allow _z to work.# z.private_name = '_z'# or_z=PrivateAttr(default=0)# field_property.PrivateAttrp=Props()print(p)p.x=2p.y=1.5print(p)assertp.x==5,'{}!={}'.format(p.x,5)assertp.y==1,'{}!={}'.format(p.y,1)msg=p.dict()assertp.x==msg['x'],'{}!={}'.format(p.x,msg['x'])assertp.y==msg['y'],'{}!={}'.format(p.y,msg['y'])assertp.z==msg['z'],'{}!={}'.format(p.z,msg['z'])Pydantic Notes ExamplePydantic __dict__ Example below does not work, but shows what pydantic is doing in the background.frompydanticimportBaseModel,PrivateAttrclassMyModel(BaseModel):x:int=1# Property doesn't really work. This is to show what pydantic does._y:int=PrivateAttr(default=1)@propertydefy(self):returnself._y@y.setterdefy(self,value):self._y=valuedefset_point(self,x,y):self.x=xself._y=ym=MyModel()m.x=2# This actually sets self.__dict__['x'] = 2assertm.dict()=={'x':2}m.y=3# Essentially this would change self.__dict__['y'] = 2assertm.dict()=={'x':2,'y':3}assertm.__dict__=={'x':2,'y':3}# This sets self.__dict__['x'] = 4 and the instance value m._y to 5, but does not change self.__dict__['y']m.set_point(4,5)m.dict()=={'x':4,'y':3}# y is not updated ._y is 5. self.__dict__['y'] still == 3# This is why field_property must update __dict__ for all field_property values.# This makes the field_property inefficient.
Package: pydantic-pynamodb
Wrap pynamo models in pydantic schemas to make them easy to work with in FastAPI.FeaturesTODORequirementspydanticpynamodbInstallationYou can installPydantic PynamodbviapipfromPyPI:$pipinstallpydantic-pynamodbUsagePlease see theCommand-line Referencefor details.ContributingContributions are very welcome.
To learn more, see theContributor Guide.LicenseDistributed under the terms of theMIT license,Pydantic Pynamodbis free and open source software.IssuesIf you encounter any problems,
pleasefile an issuealong with a detailed description.CreditsThis project was generated from@cjolowicz’sHypermodern Python Cookiecuttertemplate.
Package: pydantic-python-regex-validator
A regex parser for Pydantic, using pythons regex validator.Since pydantic V2, pydantics regex validator has some limitations. It cannot do look arounds.
There is some documenation on how to get around this. This package simplifies things for developersWe provide the class, Regex, which can be used.Usage in PydanticTo use simply do:frompydantic_python_regex_validatorimportRegexfrompydanticimportBaseModelfromtypingimportAnnotatedclassMyModel(BaseModel):my_field:Annotated[str,Regex(r'^foo')]This will then have field,my_field, which will have the regex constraint^fooUsage in FastAPIThis can also be used with fastapi.frompydantic_python_regex_validatorimportRegexQuery,RegexBodyfromfastapiimportFastAPIapp=FastAPI()@app.get("/test")asyncdefget_endpoint(my_param:RegexQuery("^foo")):returnmy_param@app.post("/test")asyncdefpost_endpoint(my_param:RegexBody("^foo")):returnmy_paramThis then has an endpoint at/testwhich takes a param,my_param, which has the regex constraint^foo
Package: pydantic-quantlib
Pydantic QuantLibQuantLib Python Objects with TypingFree software: MIT licenseDocumentation:https://pydantic-quantlib.readthedocs.io.FeaturesThis package usespydanticto wrapQuantLibto provide a set of Typed class factories.The pydantic models are auto-generated from the QuantLib SWIG bindings. The autogen code is available on request.In the following example we construct a European Option.importpydantic_quantlibaspqlpayoff=pql.PlainVanillaPayoff(type=pql.OptionType.Put,strike=40)european_exercise=pql.EuropeanExercise(date=pql.Date(d=4,m=1,y=2022))european_option=pql.VanillaOptionBase(payoff=payoff,exercise=european_exercise)The option can be converted to the usualQuantLibobject for computation as seen in this fullerexample.>>>european_option.to_quantlib()'<QuantLib.QuantLib.VanillaOption; proxy of <Swig Object of type 'ext::shared_ptr<VanillaOption>*' at 0x7f6559ddabd0> >'it can also be printed:>>>print(european_option)'PlainVanillaPayoff(type=<OptionType.Put: -1>, strike=40.0) exercise=EuropeanExercise(date=Date0(d=4.0, m=1.0, y=2022.0))'it can be converted to JSON:>>>european_option.json()'{"resource_name": "VanillaOption", "payoff": {"resource_name": "PlainVanillaPayoff", "type": -1, "strike": 40.0}, "exercise": {"resource_name": "EuropeanExercise", "date": {"resource_name": "Date", "d": 4, "m": 1, "y": 2022}}}'and it can be loaded from JSON:>>>json_repr='{"resource_name": "VanillaOption", "payoff": {"resource_name": "PlainVanillaPayoff", "type": -1, "strike": 40.0}, "exercise": {"resource_name": "EuropeanExercise", "date": {"resource_name": "Date", "d": 4, "m": 1, "y": 2022}}}'>>>pql.VanillaOption.parse_obj(json.loads(json_repr))CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2021-01-04)First release on PyPI.
Package: pydantic-remote-config
pydantic-remote-configLibrary that extendspydantic's BaseSettings modeland integrates with various remote sources to fetch application secrets & configuration.
Supported remote sources include:AWS Secrets ManagerAWS SSM Parameter StoreInstallationFor AWS services support:$pipinstallpydantic-remote-config[aws]UsageSimple Examplefrompydantic_remote_config.awsimportSecretsManager,SSMParamfrompydantic_remote_configimportRemoteSettingsclassSettings(RemoteSettings):param_1:str=SSMParam("/foo/bar/param")param_2:int=SSMParam("/foo/bar/num_param")secret:str=SecretsManager("test-secret")settings=Settings()print(settings)#> Settings(param_1="remote param", param_2=101, secret="super secret code")Templating stringsStrings can be templated using attributes that have been defined in the class and have
corresponding environment variables set. This is useful in cases where a value is
stored under a different path depending on the environment.In this example if the environment variableENVis set todev, the/app-name/dev/db_passwordvalue will be retrieved.frompydantic_remote_config.awsimportSSMParamfrompydantic_remote_configimportRemoteSettingsclassSettings(RemoteSettings):env:strdb_password:str=SSMParam("/app-name/{env}/db_password")Accessing Nested ValuesKey value pairs can be accessed by specifying thekeyarg. The example below
illustrates an example where only the database password is retrieved from a json
object.SSM Param value for/app-name/database_info:{"host":"foo.rds.aws.com","port":5432,"username":"db_user","password":"super-secret-password"}Remote config implementation:frompydantic_remote_config.awsimportSSMParamfrompydantic_remote_configimportRemoteSettingsclassSettings(RemoteSettings):db_password:str=SSMParam("/app-name/database_info",key="password")Class ConfigurationEach remote source or class of sources has its own configuration class that
can be set.AWSThe AWS config class supports specifying an aws region to fetch configuration
from. Note that this will override the default aws region configured on the
machine or boto3.frompydantic_remote_config.awsimportSecretsManager,SSMParamfrompydantic_remote_configimportRemoteSettingsfrompydantic_remote_config.configimportAWSConfigclassSettings(RemoteSettings):env:strparam:str=SSMParam("/foo/bar")secret:dict=SecretsManager("test-secret")classConfig:aws=AWSConfig(region='us-west-2')MyPy SupportThis library works with mypy!RoadmapThis library aims to be the one stop shop for python applications that need
to fetch configuration from remote sources regardless of source. Services
that are supported or on the roadmap are listed below.AWS Secrets ManagerAWS SSM Parameter StoreHashicorp VaultHashicorp ConsulAzure Key VaultIf you'd like to add a service to our roadmap, please open an issue and we'll
be happy to get it added.ContributingWIPDevelopment Dependenciesasdffor managing multiple python versionpre-commitfor formatting & linting code before commitspoetrymanaging dependencies & publishing the packageInstalling Development Dependencies
Package: pydantic-requests
Marriage of Pydantic and RequestsA helper that integrates Pydantic with requests library for seamless access to defined Models.ExamplefromenumimportEnumfrompydanticimportBaseModelfrompydantic_requestsimportPydanticSessionclassDNSStatus(Enum):"""DNS OP response codes.ref: https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6"""# No Error = 0NoError=0# Format Error = 1FormErr=1# Server FailureServFail=2# Non-Existent DomainNXDomain=3classDNSQuery(BaseModel):Status:DNSStatusclassConfig:"""Configure DNS query."""allow_mutation=Falsearbitrary_types_allowed=TruewithPydanticSession({200:DNSQuery},headers={"accept":"application/dns-json"})assession:domain="dz0ny.xyz"res=session.get("https://cloudflare-dns.com/dns-query",params={"name":domain,"type":"NS"})res.raise_for_status()query:DNSQuery=res.modelifquery.Status==DNSStatus.NXDomain:print("Domain is not registered.")else:print("Domain is registered.")
Package: pydantic-sarif
PySarifThis is a simple pydantic model for the SARIF format, generated with datamodel-codegen.InstallationpipinstallpysarifUsageStaticAnalysisResultsFormatSarifVersion210JsonSchemais likely the class that you'll be referencing the most.Examplefrompydantic_sarif.modelimportStaticAnalysisResultsFormatSarifVersion210JsonSchemaasReportexample_json=""""""report:Report=Report.parse_raw(example_json)assertreport.version=="2.1.0"
Package: pydantic-schemaorg
pydantic_schemaorgUseSchema.orgtypes inpydantic!Pydantic_schemaorgcontains all the models defined by schema.org. The pydantic classes are auto-generated from the
schema.org model definitions that can be found
onhttps://schema.org/version/latest/schemaorg-current-https.jsonldRequirementsWorks with python >= 3.8How to installpip install pydantic-schemaorgImport any class you want to use by with the following conventionfrom pydantic_schemaorg.<SCHEMAORG_MODEL_NAME> import <SCHEMAORG_MODEL_NAME>A full (hierarchical) list of Schema.org model names can be foundhereExample usagesfrom pydantic_schemaorg.ScholarlyArticle import ScholarlyArticle

scholarly_article = ScholarlyArticle(url='https://github.com/lexiq-legal/pydantic_schemaorg',
                                    sameAs='https://github.com/lexiq-legal/pydantic_schemaorg',
                                    copyrightNotice='Free to use under the MIT license',
                                    dateCreated='15-12-2021')
print(scholarly_article.json()){"@type": "ScholarlyArticle", "url": "https://github.com/lexiq-legal/pydantic_schemaorg", "sameAs": "https://github.com/lexiq-legal/pydantic_schemaorg", "copyrightNotice": "Free to use under the MIT license", "dateCreated": "15-12-2021"}
Package: pydantic-settings
pydantic-settingsSettings management using Pydantic, this is the new official home of Pydantic'sBaseSettings.This package was kindly donated to thePydantic organisationby Daniel Daniels, seepydantic/pydantic#4492for discussion.For the old "Hipster-orgazmic tool to manage application settings" package, seeversion 0.2.5.Seedocumentationfor more details.
Package: pydantic-settings-external
Pydantic Settings ExternalThe project is currently under active development.Pydantic Settings External extends Pydantic Settings to support various types of external configuration providers, such as GCP Secret Manager and AWS Secrets Manager. PyDantic Settings External has been developed using a clear abstraction, allowing for easy extension to external providers.Installation:pipinstallpydantic-settings-externalUsage example withwith_settings_externalhelperPydantic v2.xpipinstallpydantic
pipinstallpydantic-settings-external
pipinstallpydantic-settingsfrompydanticimportFieldfrompydantic_settings_externalimportBaseSettingsgcp=GCPProvider(...)one_password=OnePasswordProvider(...)classSettings(BaseSettings):SENDGRID_API_KEY:str=Field(...,json_schema_extra={"provider":{"instance":gcp,"options":{"name":"sendgrid-api-key","vesion":"latest"},"hint":"The optional hint will be displayed if the secret couldn't be retrieved for any reason.",},})ADMIN_USER:str=Field(...,json_schema_extra={"provider":{"instance":one_password,"options":{"field":"user","vault":"admin_credentials"},},})settings=Settings()Pydantic v1.10.xpipinstall"pydantic>=1.10,<2"pipinstallpydantic-settings-externalNOTE: For Pydantic v1.10.x replacejson_schema_extrawithextra.