Saravanan666/pypi-org huggingface dataset:
Package: pydano
pydanoPython library to interact with cardano network. This is essentially a wrapper aroundcardano_cli.InstallingInstall usingpippip install pydano==0.0.6Sending ADA from one wallet to other walletspydano-cli --input_address addr_test1vqe6pyeqq66nffkku7ra8xhss97nzltclgnhn20u7xyhzwcu5zzvt --pay execute_transaction.json --signing_key keys/payment2.skeyTransactions to be executed written in a JSON file with the following format:[
    {
	"address": "addr_test1vqe6pyeqq66nffkku7ra8xhss97nzltclgnhn20u7xyhzwcu5zzvt",
	"quantity": 1379280,
	"token_name": "lovelace"
    },
    {
	"address": "addr_test1vqe6pyeqq66nffkku7ra8xhss97nzltclgnhn20u7xyhzwcu5zzvt",
	"quantity": 1,
	"token_name": "29270c0384408dcf4fae241d756ec7632f9bb9a2abb2627d371bc262.cheekyunttest10"
    }
]We use the input address as thechange_addressfor ADA and non-ADA assets.Minting TokensCommand:pydano-cli --input_address addr_test1vqe6pyeqq66nffkku7ra8xhss97nzltclgnhn20u7xyhzwcu5zzvt --mint mint_transaction.json --signing_key keys/payment2.skey --minting_script data/policy.script --log_level DEBUG --min_utxo 1758582Pass the assets to be minted using the--mintoption. An example of a file is:[
    {
	"address": "addr_test1vqe6pyeqq66nffkku7ra8xhss97nzltclgnhn20u7xyhzwcu5zzvt",
	"token_name": "cheekyunttest41"
    },
    {
	"address": "addr_test1vqe6pyeqq66nffkku7ra8xhss97nzltclgnhn20u7xyhzwcu5zzvt",
	"token_name": "cheekyunttest40"
    }

]Connecting to remote cardano node instead of starting node on your laptop.Grab the latest cardano binary fromDownload LinkExtractcardano-clilocally by extracting the downloaded package.tar xzfv cardano-node-1.29.0-linux.tar.gzInstallcardano-*binaries on local path.cp cardano-* $HOME/.local/bin/[Optional] Start socat on your server, where actual node is running.nohup socat TCP-LISTEN:8080,fork,reuseaddr, UNIX-CONNECT:$CARDANO_NODE_SOCKET_PATH&Start socat on your local machine, to connect to socket on remote node.socat UNIX-LISTEN:node.socket,fork,reuseaddr,unlink-early, TCP:<IP_ADDR>:8080[Replace <IP_ADDR> with ip of your remote machine]Export the path ofpwd/node.socketasCARDANO_NODE_SOCKET_PATHWe are using 8080 port for communication between our remote node and local node here. Make sure:8080 port is open on remote host.echo $CARDANO_NODE_SOCKET_PATHpoints to the correct location of socketP.S: refer to the./scripts/run_socat.shto starting socat locally.P.S: This is untested code, and loss incurred due to the use of this library is not our responsibility!!!
Package: pydantic2-argparse
Pydantic ArgparseTyped Argument Parsing with PydanticHelpSeedocumentationfor help.InstallationInstallation withpipis simple:$pipinstallpydantic2-argparseExampleimportpydanticimportpydantic2_argparseclassArguments(pydantic.BaseModel):# Required Argsstring:str=pydantic.Field(description="a required string")integer:int=pydantic.Field(description="a required integer")flag:bool=pydantic.Field(description="a required flag")# Optional Argssecond_flag:bool=pydantic.Field(False,description="an optional flag")third_flag:bool=pydantic.Field(True,description="an optional flag")defmain()->None:# Create Parser and Parse Argsparser=pydantic2_argparse.ArgumentParser(model=Arguments,prog="Example Program",description="Example Description",version="0.0.1",epilog="Example Epilog",)args=parser.parse_typed_args()# Print Argsprint(args)if__name__=="__main__":main()$python3example.py--helpusage: Example Program [-h] [-v] --string STRING --integer INTEGER --flag |--no-flag [--second-flag] [--no-third-flag]Example Descriptionrequired arguments:--string STRING    a required string--integer INTEGER  a required integer--flag, --no-flag  a required flagoptional arguments:--second-flag      an optional flag (default: False)--no-third-flag    an optional flag (default: True)help:-h, --help         show this help message and exit-v, --version      show program's version number and exitExample Epilog$python3example.py--stringhello--integer42--flagstring='hello' integer=42 flag=True second_flag=False third_flag=TrueLicenseThis project is licensed under the terms of the MIT license.
Package: pydantic2graphene
pydantic2grapheneEasy way to convert pydantic2graphene models to graphene objects.Install$ pip install pydantic2grapheneA Simple ExampleUsingto_grapheneimportpydanticimportpydantic2grapheneclassUser(pydantic.BaseModel):email:stractive:bool=FalseUserGql=pydantic2graphene.to_graphene(User)Converting to multiple graphene types withConverterToGrapheneBaseimportpydanticimportpydantic2grapheneclassUser(pydantic.BaseModel):email:stractive:bool=FalseclassUserConverter(pydantic2graphene.ConverterToGrapheneBase):classConfig:model=UserUserGql=UserConverter.as_class()# graphene.ObjectTypeUserInputGql=UserConverter.as_class(graphene.InputObjectType)UserInterfaceGql=UserConverter.as_class(graphene.Interface)More Examples
Package: pydantic_aiohttp
pydantic_aiohttp - Symbiosis ofPydanticandAiohttpThis repository provides simple HTTP Client based on aiohttp with integration of pydanticExamplesBasic exampleimportasyncioimportpydanticfrompydantic_aiohttpimportClientfrompydantic_aiohttp.responsesimport(JSONResponseClass,PlainTextResponseClass,PydanticModelResponseClass)classTodo(pydantic.BaseModel):userId:intid:inttitle:strcompleted:boolasyncdefmain():client=Client('https://jsonplaceholder.typicode.com')asyncwithclient:# Text responsetodo=awaitclient.get('/todos/1',response_class=PlainTextResponseClass)print(isinstance(todo,str))# True# JSON Responsetodo=awaitclient.get('/todos/1',response_class=JSONResponseClass)print(isinstance(todo,dict))# True# You can achieve the same result if you know exact shape of response, dict for exampletodo=awaitclient.get('/todos/1',response_class=PydanticModelResponseClass,response_model=dict)print(isinstance(todo,dict))# True# Deserialization in pydantic modeltodo=awaitclient.get('/todos/1',response_class=PydanticModelResponseClass,response_model=Todo)print(isinstance(todo,Todo))# True# PydanticModelResponseClass is used by default, so you can omit ittodo=awaitclient.get('/todos/1',response_model=Todo)print(isinstance(todo,Todo))# Trueif__name__=='__main__':asyncio.run(main())Explicitly close connectionimportasyncioimportpydanticfrompydantic_aiohttpimportClientclassTodo(pydantic.BaseModel):userId:intid:inttitle:strcompleted:boolasyncdefmain():client=Client('https://jsonplaceholder.typicode.com')try:awaitclient.get('/todos/1',response_model=Todo)finally:# Don't forget to close client session after useawaitclient.close()if__name__=='__main__':asyncio.run(main())Downloading filesimportasyncioimportuuidfrompydantic_aiohttpimportClientasyncdefmain():client=Client('https://source.unsplash.com')asyncwithclient:filepath=awaitclient.download_file("/random",filepath=f"random_{uuid.uuid4()}.jpg")print(filepath)if__name__=='__main__':asyncio.run(main())Handling errors parsed as pydantic modelsimporthttpimportasyncioimportpydanticimportpydantic_aiohttpfrompydantic_aiohttpimportClientclassFastAPIValidationError(pydantic.BaseModel):loc:list[str]msg:strtype:strclassFastAPIUnprocessableEntityError(pydantic.BaseModel):detail:list[FastAPIValidationError]classUser(pydantic.BaseModel):id:stremail:strfirst_name:strlast_name:stris_admin:boolasyncdefmain():client=Client("https://fastapi.example.com",error_response_models={http.HTTPStatus.UNPROCESSABLE_ENTITY:FastAPIUnprocessableEntityError})try:# Imagine, that "email" field is required for this routeawaitclient.post("/users",body={"first_name":"John","last_name":"Doe"},response_model=User)exceptpydantic_aiohttp.HTTPUnprocessableEntityase:# response field of exception now contain parsed pydantic model entityprint(e.response.detail[0].model_dump_json(indent=4))# >>># {#     "loc": [#         "body",#         "email"#     ],#     "msg": "field required",#     "type": "value_error.missing"# }finally:awaitclient.close()if__name__=='__main__':asyncio.run(main())LICENSEThis project is licensed under the terms of theMITlicense.
Package: pydantic-annotated
pydantic-annotatedProof of conceptDecomposing Field components into Annotated.fromtypingimportAnnotatedfrompydantic_annotatedimportBaseModel,Description,FieldAnnotationModelclassPII(FieldAnnotationModel):status:boolclassComplexAnnotation(FieldAnnotationModel):x:inty:intclassPatient(BaseModel):name:strcondition:Annotated[str,ComplexAnnotation(x=1,y=2),Description("Patient condition"),PII(status=True),]
Package: pydantic-appconfig
Ever wanted to useAWS AppConfigfor your Python app, but can’t bear configs withoutpydantic?Well, your days of using evil.envor.inifiles,ENVIRONMENTvariables or even custom providers is over!With just a simplepipinstallpydantic-appconfigWith a lot of inspiration from this AWSsample.Introducingpydantic_appconfig.Set yourself up with your favouritepydantic.BaseModel:classMyAppConfig(pydantic.BaseModel):"""My app config."""test_field_string:strtest_field_int:intclassConfig:"""The pydantic config, including title for the JSON schema."""title="MyAppConfig"Set up the config helper using your shiny config class:frompydantic_appconfigimportAppConfigHelpermy_config:AppConfigHelper[MyAppConfig]=AppConfigHelper(appconfig_application="AppConfig-App",appconfig_environment="AppConfig-Env",appconfig_profile="AppConfig-Profile",max_config_age=15,fetch_on_init=True,config_schema_model=MyAppConfig,)Use it:my_val=my_config.config.test_field_stringAWS AppConfig also has support forvalidators.Pydantic is able to generate a JSON schema for you to upload:print(MyAppConfig.schema_json(indent=2)){"title":"MyAppConfig","description":"My app config.","type":"object","properties":{"test_field_string":{"title":"Test Field String","type":"string"},"test_field_int":{"title":"Test Field Int","type":"integer"}},"required":["test_field_string","test_field_int"]}
Package: pydantic-apply
pydantic-applyInstallationJust usepip install pydantic-applyto install the library.Note:pydantic-applyis compatible withpydanticversions1.9,1.10and even2.x(🥳) on
Python3.8,3.9,3.10and3.11. This is also ensured running all tests on all those versions
usingtox.AboutWithpydantic-applyyou can apply changes to your pydantic models by using
theApplyModelMixinit provides:importpydanticfrompydantic_applyimportApplyModelMixinclassSomething(ApplyModelMixin,pydantic.BaseModel):name:strage:intobj=Something(name='John Doe',age=42)obj.model_apply({"age":43,})assertobj.age==43As the apply data you may pass any dictionary or other pydanic object as you
wish. pydantic objects will be converted to dict's when being applied - but will
only use fields that where explicitly set on the model instance. Also note
that.apply()will ignore all fields not present in the model, like the
model constructor would.Nested modelspydantic-applywill also know how to apply changes to nested models. If those
models are by themself subclasses ofApplyModelMixinit will callapply()on those fields as well. Otherwise the whole attribute will be replaced.Apply changes when usingvalidate_assignmentWhen your models havevalidate_assignmentenabled it may become tricky to
apply changes to the model. This is due to the fact that you only can assign
fields once at a time. But withvalidate_assignmentenabled this means each
field assignment will trigger its own validation and this validation might
fail as the model state is not completely changes and thus in a "broken"
intermediate state.pydantic-applywill take care of this issue and disable the validation for
each assignment while applying the changes. It will also ensure the resulting
object will still pass the validation, so you don't have to care about this
case at all.ContributingIf you want to contribute to this project, feel free to just fork the project,
create a dev branch in your fork and then create a pull request (PR). If you
are unsure about whether your changes really suit the project please create an
issue first, to talk about this.
Package: pydantic-argify
pydantic-argifyBuild ArgumentParser from pydantic model.What's difference with other projects.This project is dedicated to crafting an argument parser based on the Pydantic model.
Unlike many other projects where the ArgumentParser functionality is concealed within the library,
this tool aims to simplify its use, even in complex scenarios.
For instance, handling nested sub-parsers likeaws s3 cp <some options>or supporting nested Pydantic models has been a challenge in existing solutions.
This library overcomes these limitations, allowing you to effortlessly incorporate intricate functionalities.</code></pre><h2>Example1</h2><prelang="python"><code>fromargparseimportArgumentParserfrompydanticimportBaseModel,Fieldfrompydantic_argifyimportbuild_parserclassConfig(BaseModel):string:str=Field(description="string parameter")integer:int=Field(description="integer parameter")parser=ArgumentParser()build_parser(parser)parser.print_help()usage: basic.py [-h] --string STRING --integer INTEGER

optional arguments:
  -h, --help            show this help message and exit

Config:
  --string STRING, -s STRING
                        a required string
  --integer INTEGER, -i INTEGER
                        a required integerExample 2fromargparseimportArgumentParserfrompydanticimportBaseModel,Fieldfrompydantic_argifyimportbuild_parserclassSubConfigA(BaseModel):string:str=Field(description="string parameter")integer:int=Field(description="integer parameter")classSubConfigB(BaseModel):double:float=Field(description="a required string")integer:int=Field(0,description="a required integer")parser=ArgumentParser()subparsers=parser.add_subparsers()build_parser(subparsers.add_parser("alpha"),SubConfigA)build_parser(subparsers.add_parser("beta"),SubConfigB)parser.print_help()usage: sub_parser.py [-h] {alpha,beta} ...

positional arguments:
  {alpha,beta}

optional arguments:
  -h, --help    show this help message and exitAdditional configBehaviour of pydantic can be controlled via theConfigclass or extra arguments ofField.Configis affected all fields.
Extra arguments ofFieldis affected specific field.cli_disable_prefixPrefix of argument of boolean type for `store_false`. Default to--disable-cli_enable_prefixPrefix of argument of boolean type for `store_true`. Default to--enable-Future works[ ]: Options completion for bash
Package: pydantic-argparse
Pydantic ArgparseTyped Argument Parsing with PydanticHelpSeedocumentationfor help.InstallationInstallation withpipis simple:$pipinstallpydantic-argparseExampleimportpydanticimportpydantic_argparseclassArguments(pydantic.BaseModel):# Required Argsstring:str=pydantic.Field(description="a required string")integer:int=pydantic.Field(description="a required integer")flag:bool=pydantic.Field(description="a required flag")# Optional Argssecond_flag:bool=pydantic.Field(False,description="an optional flag")third_flag:bool=pydantic.Field(True,description="an optional flag")defmain()->None:# Create Parser and Parse Argsparser=pydantic_argparse.ArgumentParser(model=Arguments,prog="Example Program",description="Example Description",version="0.0.1",epilog="Example Epilog",)args=parser.parse_typed_args()# Print Argsprint(args)if__name__=="__main__":main()$python3example.py--helpusage: Example Program [-h] [-v] --string STRING --integer INTEGER --flag |--no-flag [--second-flag] [--no-third-flag]Example Descriptionrequired arguments:--string STRING    a required string--integer INTEGER  a required integer--flag, --no-flag  a required flagoptional arguments:--second-flag      an optional flag (default: False)--no-third-flag    an optional flag (default: True)help:-h, --help         show this help message and exit-v, --version      show program's version number and exitExample Epilog$python3example.py--stringhello--integer42--flagstring='hello' integer=42 flag=True second_flag=False third_flag=TrueLicenseThis project is licensed under the terms of the MIT license.
Package: pydantic-argparse-builder
pydantic-argparse-builderBuild ArgumentParser from pydantic model.What's difference with other projects.This project focuses on creating an argument parser from the pydantic model.
Many other projects hideArgumentParserin the library, but it is difficult to use in complicated cases.
For example nested sub parser; i.e.aws s3 cp <some options>, or nested pydantic model is not supported.
This library achieve that you can easily add complicate uses.Example 1fromargparseimportArgumentParserfrompydanticimportBaseModel,Fieldfrompydantic_argparse_builderimportbuild_parserclassConfig(BaseModel):string:str=Field(description="string parameter")integer:int=Field(description="integer parameter")parser=ArgumentParser()build_parser(parser)parser.print_help()usage: basic.py [-h] --string STRING --integer INTEGER

optional arguments:
  -h, --help            show this help message and exit

Config:
  --string STRING, -s STRING
                        a required string
  --integer INTEGER, -i INTEGER
                        a required integerExample 2fromargparseimportArgumentParserfrompydanticimportBaseModel,Fieldfrompydantic_argparse_builderimportbuild_parserclassSubConfigA(BaseModel):string:str=Field(description="string parameter")integer:int=Field(description="integer parameter")classSubConfigB(BaseModel):double:float=Field(description="a required string")integer:int=Field(0,description="a required integer")parser=ArgumentParser()subparsers=parser.add_subparsers()build_parser(subparsers.add_parser("alpha"),SubConfigA)build_parser(subparsers.add_parser("beta"),SubConfigB)parser.print_help()usage: sub_parser.py [-h] {alpha,beta} ...

positional arguments:
  {alpha,beta}

optional arguments:
  -h, --help    show this help message and exitAdditional configBehaviour of pydantic can be controlled via theConfigclass or extra arguments ofField.Configis affected all fields.
Extra arguments ofFieldis affected specific field.cli_disable_prefixPrefix of argument of boolean type for `store_false`. Default to--disable-cli_enable_prefixPrefix of argument of boolean type for `store_true`. Default to--enable-Future works[ ]: Options completion for bash
Package: pydantic-argparse-extensible
pydantic-argparse-extensibleA typed wrapper forargparseleveragingpydanticto
generate command line interfaces.Thepydantic_argparse_extensibleprovides anArgModelclass, which inherits
frompydantic.BaseModeland provides a few new methods. For simple arguments,
there's not much you need to do:frompydanticimportConfigDictfrompydantic_argparse_extensibleimportArgModelclassArgs(ArgModel):model_config=ConfigDict(use_attribute_docstrings=True)user:str"""The username to connect to."""host:str"""The host to connect to."""defmain()->None:args=Args.argparse()print(args)if__name__=="__main__":main()# $ python -m example_simple --help# usage: example_simple.py [-h] --user USER --host HOST## options:#   -h, --help   show this help message and exit#   --user USER  The username to connect to.#   --host HOST  The host to connect to.Then,pydantichelps ensure that all the data fromargparseis typed as you
expect. Plus, we get autocompletion for argument fields on theArgsclass, as
well as hover documentation that matches the CLI--helpoutput.You can useArgModels as reusable sets of arguments. Here,Argswill
include arguments defined on both of the models it includes:classCommonArgs(ArgModel):passclassGitHubArgs(ArgModel):passclassArgs(ArgModel):common:CommonArgsgithub:GitHubArgsThe power ofpydantic_argparse_extensiblelies in letting you opt out of its
automatic generation logic in order to manually create more complex
command-line interfaces that aren't supported bytyperand other
alternatives:classAddress(BaseModel):user:strhost:strclassEc2Instance(BaseModel):address:Addressinstance_id:strclassArgs(ArgModel):deploy:boolsystem_profile:Path=Path("/nix/var/nix/profiles/system")aws_role_arn:str|None=Noneec2_instances:list[Ec2Instance]@classmethoddefupdate_argparser(cls,parser:ArgumentParser,manual:set[str]|None=None)->None:parser.add_argument("--no-deploy",action="store_false",dest="deploy",help="Don't deploy the resulting builds.",)# This argument doesn't appear as a field at all, but it's used to help# define the `ec2_instances` field.parser.add_argument("--ssh-user",help="Username to use when connecting to `--ec2-instance` hosts via SSH.",)parser.add_argument("--ec2-instance",nargs=2,metavar=("HOST_NAME","INSTANCE_ID"),dest="ec2_instances",help="AWS EC2 instances to deploy to, if any.",)# We defined arguments for the `deploy` and `ec2_instances` fields# manually, so we tell `pydantic_argparse_extensible` to skip them when# generating the CLI.super().update_argparser(parser,manual={"deploy","ec2_instances"})@classmethoddeffrom_parsed_args(cls,args:Namespace,partial:dict[str,Any]|None=None)->Self:ec2_instances=[]ssh_user=args.ssh_userifargs.ec2_instances:ec2_instances=[Ec2Instance(address=Address(user=ssh_user,host=host),instance_id=instance_id)for(host,instance_id)inargs.ec2_instances]# We parsed the value for the `ec2_instances` field manually, so we# tell `pydantic_argparse_extensible` to ignore the `ec2_instances`# attribute on the `args` when constructing the model.partial={"ec2_instances":ec2_instances}returnsuper().from_parsed_args(args,partial)
Package: pydantic-ast
Pydantic ASTPydantic models covering Python AST types.Installationpipinstallpydantic-astUsageUse it as a drop-in replacement toast.parsewith a more readable representation.>>>importast>>>importpydantic_ast>>>source="x = 1">>>ast.parse(source)<ast.Moduleobjectat0x7fef82567610>>>>pydantic_ast.parse(source)pydantic-ast:body=[Assign(targets=[Name(id='x',ctx=Store())],value=Constant(value=1),type_comment=None)]type_ignores=[]Use it on the command line to quickly get an AST of a Python program or a section of oneecho'"Hello world"'|pydantic-ast⇣body=[Expr(value=Constant(value='Hello world'))] type_ignores=[]Use it on ASTs you got from elsewhere to make them readable, or to inspect parts of them more easily.
TheAST_to_pydanticclass is aast.NodeTransformerthat converts nodes in the AST topydantic_astmodel types when the tree nodes are visited.>>>frompydantic_astimportAST_to_pydantic>>>source="123 + 345 == expected">>>my_mystery_ast=ast.parse(source)>>>ast_model=AST_to_pydantic().visit(my_mystery_ast)>>>ast_modelbody=[Expr(value=Compare(left=BinOp(left=Constant(value=123),op=Add(),right=Constant(value=345)),ops=[Eq()],comparators=[Name(id='expected',ctx=Load())]))]type_ignores=[]>>>ast_model.body[Expr(value=Compare(left=BinOp(left=Constant(value=123),op=Add(),right=Constant(value=345)),ops=[Eq()],comparators=[Name(id='expected',ctx=Load())]))]It's simply much easier to drill down into a tree when you can see the fields in a repr.>>>ast_model.body[0].valueCompare(left=BinOp(left=Constant(value=123),op=Add(),right=Constant(value=345)),ops=[Eq()],comparators=[Name(id='expected',ctx=Load())])>>>ast_model.body[0].value.leftBinOp(left=Constant(value=123),op=Add(),right=Constant(value=345))>>>ast_model.body[0].value.left.leftConstant(value=123)>>>ast_model.body[0].value.left.left.value123DevelopmentTo set up pre-commit hooks (to keep the CI bot happy) runpre-commit install-hooksso all git
commits trigger the pre-commit checks. I useConventional Commits.
This runsblack,flake8,autopep8,pyupgrade, etc.To set up a dev env, I first create a new conda environment and use it in PDM withwhich python > .pdm-python.
To usevirtualenvenvironment instead of conda, skip that. Runpdm installand a.venvwill be created if no
Python binary path is found in.pdm-python.To run tests, runpdm run python -m pytestand the PDM environment will be used to run the test suite.