Saravanan666/pypi-org huggingface dataset:
Package: typedjson
typedjsonJSON decoding for Python with type hinting (PEP 484).Requirements and RestrictionsPython >= 3.6Mypy <= 0.770Use non-generic or parameterized class to decode JSON.Use type hints without forward references.FeaturesSupport decoding types as below:primitive types likestr,int,float,boolandNone.UnionandOptional.homogeneous and heterogeneousTupleandList.variable-lengthTuple.non-generic and parameterized dataclasses.Support API likejson.loadandjson.loads.ExamplefromtypingimportOptionalimporttypedjsonfromdataclassesimportdataclass@dataclass(frozen=True)classNameJson:first:strlast:Optional[str]@dataclass(frozen=True)classCatJson:id:strage:intname:Optional[NameJson]json={'id':'test-cat','age':13,'name':{'first':'Jiji',},}print(typedjson.decode(CatJson,json))# Output: CatJson(id='test-cat', age=13, name=NameJson(first='Jiji', last=None))print(typedjson.decode(CatJson,{}))# Output: DecodingError(TypeMismatch(('id',)))Please refer totest codesfor more detail.ContributionsPlease readCONTRIBUTING.md.TODOProhibit decodingSetandDictexplicitly.Provide the API document.Explain why typedjson uses undocumented APIs.Explain what typedjson resolves.Improve API to dump likejson.dumpandjson.dumps.Provide mypy plugin to check whether the class is encodable as JSON or not with@typedjson.encodabledecorator.Improve the peformance oftypedjson.decode.Support type hints with forward reference.SupportTypedDict.
Package: typed-lists
typed-liststyped-listsis a library for typed, parallelized lists for Python implemented in Rust. The project was develop usingmaturin.The project heavily depends onrayonand PyO3pyo3and takes inspiration fromnumpy, Rust'sndarray, and many more packages.InstallationFrom PyPI:pipinstalltyped-listsBuild from source:maturin build -r -i=path/to/python
pip install .../typed-lists/target/wheels/<whl file name>.whlNote: requires Rust installationUsageSee./example.ipynb.Running TestsTests are run withpytest.
Package: typedload
typedloadLoad and dump json-like data into typed data structures in Python3, enforcing
a schema on the data.This module provides an API to load dictionaries and lists (usually loaded
from json) into Python's NamedTuples, dataclass, sets, enums, and various
other typed data structures; respecting all the type-hints and performing
type checks or casts when needed.It can also dump from typed data structures to json-like dictionaries and lists.It is very useful for projects that use Mypy and deal with untyped data
like json, because it guarantees that the data will follow the specified schema.It is released with a GPLv3 license butit is possible to ask for LGPLv3.ExampleFor example this dictionary, loaded from a json:data={'users':[{'username':'salvo','shell':'bash','sessions':['pts/4','tty7','pts/6']},{'username':'lop'}],}Can be treated more easily if loaded into this type:@dataclasses.dataclassclassUser:username:strshell:str='bash'sessions:List[str]=dataclasses.field(default_factory=list)classLogins(NamedTuple):users:List[User]And the data can be loaded into the structure with this:t_data=typedload.load(data,Logins)And then converted back:data=typedload.dump(t_data)Supported typesSince this is not magic, not all types are supported.The following things are supported:Basic python types (int, str, bool, float, NoneType)NamedTupleEnumOptional[SomeType]List[SomeType]Dict[TypeA, TypeB]Tuple[TypeA, TypeB, TypeC] and Tuple[SomeType, ...]Set[SomeType]Union[TypeA, TypeB]dataclassattr.sForwardRef (Refer to the type in its own definition)LiteralTypedDictdatetime.date, datetime.time, datetime.datetimere.PatternPathIPv4Address, IPv6Addresstyping.Anytyping.NewTypeUnionstypedload works fine with untagged unions. However using Literal fields to tag them makes it much faster.Using MypyMypy and similar tools work without requiring any plugins.# This is treated as Any, no checks done.data=json.load(f)# This is treated as Dict[str, int]# but there will be runtime errors if the data does not# match the expected formatdata=json.load(f)# type: Dict[str, int]# This is treated as Dict[str, int] and an exception is# raised if the actual data is not Dict[str, int]data=typedload.load(json.load(f),Dict[str,int])So when using Mypy, it makes sense to make sure that the type is correct,
rather than hoping the data will respect the format.ExtendingType handlers can easily be added, and existing ones can be replaced, so the library is fully cusomizable and can work with any type.Inheriting a base class is not required.Installpip install typedloadapt install python3-typedloadLatest and greatest .deb file is inreleasesDocumentationOnline documentationIn the docs/ directoryThe tests are hard to read but provide more in depth examples of
the capabilities of this module.Used byAs dependency, typedload is used by those entities. Feel free to add to the list.Several universities around the world (viaRelational)People who love IRC (vialocalslackirc)No clue but it gets thousands of downloads per dayaccording to pypi
Package: typedmarshal
Strongly typed (un)marshaller between Python object and JSON inspired by Golang’s “encode/json” library.Short exampleHere is a pitch for TypedMarshal.Let there be a JSON model definition:from typedmarshal import MarshalModel

class SampleModel(MarshalModel):
    name: str = None
    age: int = None
    hobbies: List[str] = []Then unmarshal JSON:js_str = '''
{
    "name": "Hatsune Miku",
    "age": 16,
    "hobbies": ["Sing a song", "Dance to music", "Eat negi"]
}
'''

js_obj = SampleModel()
js_obj.load_json(js_str)Now defined attributes are available to use:>>> js_obj.name
'Hatsune Miku'

>>> js_obj.hobbies
['Sing a song', 'Dance to music', 'Eat negi']Voila!Development progressIt’s still in alpha and unstable. Everything may change in future.ContributingTBDLicenseThis library is released under BSD License.
Package: typedmodel
TypedModelTypedModel aims to provide strict type checking for dataclass and pydantic model.dataclass is useful, but provides no type checkingpydantic is useful, but sometimes it bugs outhttps://github.com/samuelcolvin/pydantic/issues/3189https://github.com/samuelcolvin/pydantic/issues/3569UsagepipinstalltypedmodelfromtypedmodelimportBaseModelclassFoo(BaseModel):a:strb:strd='default'e:str='default'foo=Foo(a="a",b="b")checktestsfor more use cases
Package: typedobject
typedobjectDefine real, inheritable, and efficient Python classes usingTypedDict-like
syntax.Getting startedInstall from pip.python -m pip install typedobjectThen, annotate your class withtypedobjectand declare its member fields
using variable annotations.from typedobject import typedobject

@typedobject
class Point:
    x: int
    y: intThen construct the object using either positional or keyword arguments.pt1 = Point(10, 20)
pt2 = Point(x=10, y=20)
assert pt1 == pt2You can define methods, including__init__.@typedobject
class Rectangle:
    pt1: Point
    pt2: Point

    def __init__(self, x1, y1, x2, y2):
        self.pt1 = Point(x1, y1)
        self.pt2 = Point(x2, y2)

    def area(self):
        return (self.pt2.x - self.pt1.x) * (self.pt2.y - self.pt1.y)

rect = Rectangle(1, 1, 3, 3)
assert rect.area() == 4UnlikeTypedDict, the defined classes are actually fresh new classes,
notdicts.assert isinstance(rect, Rectangle)
assert not isinstance(rect, Point)Inheritance works just fine.@typedobject
class RoundedRect(Rectangle):
    corner_radius: int

rr = RoundedRect(Point(1, 1), Point(3, 3), 1)Note that the derived class overrides__init__, unless you use.no_init.@typedobject.no_init
class RoundedRect2(Rectangle):
    corner_radius: int

rr = RoundedRect2(1, 1, 3, 3)
assert not hasattr(rr, 'corner_radius')Typed object classes, unlikedataclass, specify__slots__, which makes
access to attributes faster and makes objects take less memory, but prevents
adding new fields dynamically.They also prevent multiple inheritance.# raises TypeError
class RectangleWithAPoint(Rectangle, Point):
    passYou can, however, inject mixins.class TwoDObjectMixin:
    def area(self):
        return self.width() * self.height()

@typedobject
class Rectangle2(TwoDObjectMixin):
    pt1: Point
    pt2: Point
Package: typedpy
Typedpy - Strict Type System for Pythontypedpyis a library for type-safe, strict, Python structures. It supports Python 3.9+.FeaturesFull featured, sophisticated, class-based type systemIncludes Python stubs generator that provides static type checking within the IDESupports JSON schema draft4 features, including mapping schema-to-code and code-to-schemaSerialization, deserialization between JSON-like dict and typedpy objects, including custom mapping. Support for pickling.Easily extensible.Wrapper of any class as a FieldInheritance/mixins of fields/classesEmbedded structures within structures/fields and fields within fieldsSupports the common collectionsImmutable Structures/FieldsClean Java-generics-like definitions, but more flexible. e.g.: Set[AnyOf[Integer(minimum=10), Array]], Map[String(maxLength=8), String]No dependencies on third-party libsThere are many examples under "tests/".DocumentationDetailed documentation is hereInstallationPyPI page is hereConda-Forge page is here
Package: typedspark
Typedspark: column-wise type annotations for pyspark DataFramesWe love Spark! But in production code we're wary when we see:frompyspark.sqlimportDataFramedeffoo(df:DataFrame)->DataFrame:# do stuffreturndfBecause… How do we know which columns are supposed to be indf?Usingtypedspark, we can be more explicit about what these data should look like.fromtypedsparkimportColumn,DataSet,Schemafrompyspark.sql.typesimportLongType,StringTypeclassPerson(Schema):id:Column[LongType]name:Column[StringType]age:Column[LongType]deffoo(df:DataSet[Person])->DataSet[Person]:# do stuffreturndfThe advantages include:Improved readibility of the codeTypechecking, both during runtime and lintingAuto-complete of column namesEasy refactoring of column namesEasier unit testing through the generation of emptyDataSetsbased on their schemasImproved documentation of tablesDocumentationPlease see our documentation onreadthedocs.InstallationYou can installtypedsparkfrompypiby running:pipinstalltypedsparkBy default,typedsparkdoes not listpysparkas a dependency, since many platforms (e.g. Databricks) come withpysparkpreinstalled.  If you want to installtypedsparkwithpyspark, you can run:pipinstall"typedspark[pyspark]"Demo videosIDE demohttps://github.com/kaiko-ai/typedspark/assets/47976799/e6f7fa9c-6d14-4f68-baba-fe3c22f75b67You can find the corresponding codehere.Jupyter / Databricks notebooks demohttps://github.com/kaiko-ai/typedspark/assets/47976799/39e157c3-6db0-436a-9e72-44b2062df808You can find the corresponding codehere.FAQI found a bug! What should I do?Great! Please make an issue and we'll look into it.I have a great idea to improve typedspark! How can we make this work?Awesome, please make an issue and let us know!
Package: typed-stream
typed_streamJava-like typed Stream for PythonThis library heavily uses itertools for great performance and simple code.ExamplesInexamplesare cool examples using Streams.Not yet asked questionsI'll try to answer questions that could occur.Which type-checkers do you support?Currently only mypy is fully supported, because I couldn't get the others to work properly.Why are there no changelogs?I'm too lazy. I don't know of anybody using this (except me) and I don't need to write changelogs for myself.
If you need changelogs, please create an issue.Why EUPL-1.2-or-later?🇪🇺AGPL3 is too longGoogle EUPL PolicyIs it production-ready?Probably.
Package: typedstruct
typedstructA wrapper around thestructbuilt-in modulewith support fortyping, on top of
Python 3.7dataclasses.ExampleFor example, if you wanted to read the header of BMP files, you could write
this:fromdataclassesimportdataclassfromtypedstructimportLittleEndianStruct,StructType@dataclassclassBMPHeader(LittleEndianStruct):type:int=StructType.uint16()# magic identifier: 0x4d42size:int=StructType.uint32()# file size in bytesreserved1:int=StructType.uint16()# not usedreserved2:int=StructType.uint16()# not usedoffset:int=StructType.uint32()# image data offset in bytesdib_header_size:int=StructType.uint32()# DIB header size in byteswidth_px:int=StructType.int32()# width of the imageheight_px:int=StructType.int32()# height of the imagenum_planes_px:int=StructType.uint16()# number of color planesbits_per_pixel:int=StructType.uint16()# bits per pixelcompression:int=StructType.uint32()# compression typeimage_size_bytes:int=StructType.uint32()# compression typex_resolution_ppm:int=StructType.int32()# pixels per metery_resolution_ppm:int=StructType.int32()# pixels per meternum_colors:int=StructType.int32()# number of colorsimportant_colors_colors:int=StructType.int32()# important colorswithopen("some_file.bmp","rb")asfile:raw_data=file.read(BMPHeader.get_size())bmp_header=BMPHeader.unpack(raw_data)assertbmp_header.type==0x4D42print(f"This image is{bmp_header.width_px}x{bmp_header.height_px}")
Package: typeduck
typeduckIntroductionA lightweight utility for comparing annotation declarations for their compatibility.InstallationRequires Python 3.8 or above.pipinstalltypeduckUsagefromtypingimportUnion,Listfromtypeduckimporttypes_validatesource=List[str]target=List[Union[str,int]]types_validate(source,target)# returns a boolean# ORtypes_validate(source,target,raises=True)# will raise a TypeError when validation failsUse CasesValidate annotations between functions or classes matchfromtypingimportList,Unionfromtypeduckimporttypes_validatedefmy_func()->List[str]:...defyour_func(data:List[Union[int,str]]):...source=my_func.__annotations__['return']target=your_func.__annotations__['data']are_compatible=types_validate(source,target)# TrueSee more examples in thetests.pyfile.
Package: typed-undefined
Typed UndefinedWhenNoneis not valid default value you can always useundefined.fromundefinedimportUndefined,undefined,resolvedeffoo(bar:Undefined[int]=undefined)->int:returnresolve(undefined,10)foo(1)# okfoo(1.0)# errora:Undefined[int]=1# okb:Undefined[int]=0.5# errormypy integrationYou should addundefined_mypyto list of mypy plugins:[mypy]
plugins = undefined.mypy
Package: type-enforce
type-enforce-pySupports enforcing type annotations on functions and coroutines. Complete support for types from typing module.InstallationWindowspy -m pip install type-enforceUnix/MacOSpython3-mpipinstalltype-enforceExamples1. Basic usagefromtype_enforceimportenforce_type@enforce_typedefmy_typed_fn(text:str,age:int,time:datetime.datetime.fromisoformat):print(type(text),type(age),type(time))my_typed_fn(234324,"47539",'2021-09-15T07:49:38.412586')#time in isoformat is passed to the fromisoformat classmethod of datetime class which converts it to an actual datetime class, the same goes with the first two arguments2. Usage with typing.Union, typing.Literal and other types.@enforce_typedefmyfn(val:typing.Dict[str,typing.Union[float,int]]):print(type(val),val)print(" ".join([str(type(i))+" + "+str(type(j))fori,jinval.items()]))myfn({'hello':'3453',True:'345.345'})# Output: <class 'dict'> {'hello':'3453', True: '345.345'} \n <class 'str'> + <class 'int'> <class 'str'> + <class 'float'>@enforce_typedefliteral_example(value:typing.Literal['no','yes']):print(value)literal_example('yes')#Okliteral_example('yas')#Errorliteral_example('no')#OkWhat this does under the hood ?First checks if the type of the value is one of the annotated types, if yes then returns it else tries to convert it according to the annotation if at all it is convertible if it fails, a TypeError is thrown most probably or the callable to which the value was passed could even throw a custom error for example: datetime.datetime.fromisoformat.Enjoy making your functions statically / strongly typed.
Package: type-enum
type_enum: Concise sum types in PythonSum types (aka tagged unions) in the style of Rust'senums, with pattern matching and (with the mypy plugin) exhaustiveness checking.Basic usagefromtype_enumimportField,TypeEnumclassBgColor(TypeEnum):transparent:Field[()]name:Field[str]rgb:Field[int,int,int]hsv:Field[int,int,int]background_color:BgColor=BgColor.rgb(39,127,168)assertisinstance(background_color,BgColor)assertnotisinstance(BgColor.rgb,BgColor)matchbackground_color:caseBgColor.transparent():# unfortunately needs the parenthesesprint("no color")caseBgColor.name(color_name):print(f"color name:{color_name}")caseBgColor.rgb(red,green,blue):print(f"RGB:{red},{green},{blue}")caseBgColor.hsv(hue,saturation,value):print(f"HSV:{hue},{saturation},{value}")# will print "RGB: 39, 127, 168"InstallationRequires Python >= 3.11 (because features from PEP 646 are required)pip install type-enumAnd for the mypy plugin (requires mypy >= 1.7):pip install type-enum-pluginThen register the plugin with[tool.mypy]plugins="type_enum_plugin"Advanced usageExhaustiveness checkingTo make exhaustiveness checking work, you first need the mypy plugin, and then you also need to use the specialTattribute that is synthesized for eachTypeEnum:fromtype_enumimportField,TypeEnumclassColor(TypeEnum):transparent:Field[()]name:Field[str]deff(color:Color.T)->str:matchcolor:caseColor.transparent():return"no color"caseColor.name(color_name):returncolor_nameassertf(Color.transparent())=="no color"The requirement to use.Tis a limitation of the mypy plugin, and hopefully will be removed in the future.GenericsThe.Tattribute can also be used to specify type arguments for genericTypeEnums:fromtypingimportGeneric,Tuple,Type,TypeVarfromtype_enumimportField,TypeEnumU=TypeVar("U")classMaybe(TypeEnum,Generic[U]):nothing:Field[()]some:Field[U]a=Maybe.some[int](3)deff(x:Maybe.T[int])->int:matchx:caseMaybe.some(y):returnycaseMaybe.nothing():return0assertf(a)==3
Package: type-extensions
Importable mixin methods for Python.DescriptionThetype_extensionspackage defines decorators that make it possible to define typed
extension methods outside the original class definition in a separate module. The
methods defined by atype_extensionmodule may be imported and used in other modules
without polluting the the original class definition for other modules.NoteThis project has been set up using PyScaffold 3.2. For details and usage
information on PyScaffold seehttps://pyscaffold.org/.
Package: typefactory
TypeFactoryTypeFactory is in an alpha state.  The API, types and exceptions may change significantly.TypeFactory simplifies the creation and utilisation of typed and constrained value objects.Why?Passing around primitive values (strings, ints, floats etc...) tends to led towards code checking constraints at multiple layers within a single app and subsequently to inconsistencies and bugs as constraint checks in different layers diverge.By casting the raw data as value objects based on constrained types, and using optionally type checking:domain concepts and rules can be encapsulated at the lowest possible level in value objectscode becomes clearer and tied to domain conceptsthe amount of code dedicated to data validation can be reduced and centralisedbugs related to bad data may be reducedvalidation is naturally pushed out to the application boundaries leaving code that can be focused on implementing domain logic/business rulesFeaturesextend an existing type with constraintsbuilt-in constraints for string and numeric types that match JSON Schema constraints (e.g. minimum, multiple_of, pattern etc...)create custom constraints for any typeintrospect types and values to extract and utilise their constraints, such as when creating HTML formsextended ValueError exception that reports all failing constraints for a valueExamplesDefining typesfromtypefactoryimportmake_typefromtypefactory.constraintsimportstring,numericId=make_type(str,"Id",[string.Pattern("^[A-Z2-7]{26}$")])Age=make_type(int,"Age",[numeric.Minimum(0),numeric.Maximum(150)])Username=make_type(str,"Username",[string.MinLength(4),string.MaxLength(32),string.Pattern("^[A-Za-z][A-Za-z0-9]{2,30}[A-zA-z]$")])Password=make_type(str,"Password",[string.MinLength(8),string.MaxLength(256)])Using types>>> my_age = Age(40)
>>> my_age
40
>>> type(my_age)
<class '__main__.Age'>
>>> isinstance(my_age, int)
True
>>> isinstance(my_age, Age)
TrueExceptionsTypes throw ValueErrors when their input data does not satisfy the types constraints.  All failing constraints are returned.username=Username("123")>>>ValueError:InvalidUsername(123):['Value cannot be less than 4 characters in length','Value must match pattern ^[A-Za-z][A-Za-z0-9]{2,30}[A-zA-z]$']username=Username("1username")>>>ValueError:InvalidUsername(1username):['Value must match pattern ^[A-Za-z][A-Za-z0-9]{2,30}[A-zA-z]$']Type CheckingCreated types can be used with optional type checking tools to enable type strong contracts propagate through the code base, reducing the need to assert values satisfy constraints at multiple levels within the code.Typically values will be converted to richer, constrained types at the external boundaries (e.g. incoming web request or database record) and then used internally.defregister(id:Id,username:Username,password:Password):...InstallationInstall fromPyPI:pipinstalltypefactoryRoadmapSubclass ValueError to pass back list of all failing constraintsContainer typesFunctions for creating the following from types:Flask URL convertersSqlAlchemy custom typesMarshmallow fieldsWTForms fields and widgets
Package: typefit
TypeFitTyping annotations make Python awesome, however it's complicated to keep your
data annotated when it comes from external sources like APIs. The goal of
Typefit is to help you map that external data into type-annotated native Python
objects.fromtypefitimportapifromtypingimportNamedTuple,TextclassItem(NamedTuple):id:inttitle:TextclassHackerNews(api.SyncClient):BASE_URL="https://hacker-news.firebaseio.com/v0/"@api.get("item/{item_id}.json")defget_item(self,item_id:int)->Item:passstory=HackerNews().get_item(42)print(story.title)# An alternative to VC: &#34;Selling In&#34;This is the full example of a Hacker News API client. Its functionality is
limited but in 14 lines counting white space you can build a type-safe client
for Hacker News. You'll find afull exampleattached if
you're interested.Documentation✨Documentation is there✨LicenceThis library is provided under the terms of theWTFPL.If you find it useful, you can have a look at thecontributorspage to
know who helped.
Package: typeforce
typeforceTypeforceis a CLI tool that enriches your Python environment with type annotations, empoweringmypy.In particular:Generatespy.typedfor annotated packages.Installs missed stub files and plugins.py.typedPEP-561says the following:Package maintainers who wish to support type checking of their code MUST add a marker file named py.typed to their package supporting typing.In practice, many maintainers don't know about this marker. So there are tons of packages that do have type annotations but don't havepy.typed.Typeforce checks all installed third-party packages and addspy.typedinto packages that have type annotations.stubs and pluginsOne of the breaking changesmypy 0.900 introducedis moving out allstubsand plugins for third-party packages out of mypy itself. Now, stub files for every such package should be installed manually.Typeforce scans all installed third-party packages and installs all needed stub files and plugins if available.Installationpython3-mpipinstall--usertypeforceUsagepython3-mtypeforce--exepython3.9