Saravanan666/pypi-org huggingface dataset:
Package: dataclass-compat
dataclass-compatUnified API for working with multiple dataclass-like librariesDataclass patternsThere are many libraries that implement a similar dataclass-like pattern!dataclasses.dataclassimportdataclasses@dataclasses.dataclassclassSomeDataclass:a:int=0b:str="b"c:list[int]=dataclasses.field(default_factory=list)pydantic.BaseModelimportpydanticclassSomePydanticModel(pydantic.BaseModel):a:int=0b:str="b"c:list[int]=pydantic.Field(default_factory=list)attrs.defineimportattr@attr.defineclassSomeAttrsModel:a:int=0b:str="b"c:list[int]=attr.field(default=attr.Factory(list))msgspec.StructimportmsgspecclassSomeMsgspecStruct(msgspec.Struct):a:int=0b:str="b"c:list[int]=msgspec.field(default_factory=list)etc...Unified APIThese are all awesome libraries, and each has its own strengths and weaknesses.
Sometimes, however, you just want to be able to query basic information about a
dataclass-like object, such as getting field names or types, or converting it to
a dictionary.dataclass-compatprovides a unified API for these operations (following or
extending the API fromdataclasseswhen possible).deffields(obj:Any)->tuple[Field,...]:"""Return a tuple of dataclass_compat.Field objects for the object."""defreplace(obj:Any,/,**changes:Any)->Any:"""Return a copy of obj with the specified changes."""defasdict(obj:Any)->dict[str,Any]:"""Return a dict representation of obj."""defastuple(obj:Any)->tuple[Any,...]:"""Return a tuple representation of obj."""defparams(obj:Any)->DataclassParams:"""Return parameters used to define the dataclass."""Thedataclass_compat.Fieldanddataclass_compat.DataclassParamobjects are
simple dataclasses that match the protocols ofdataclasses.Fieldand the
(private)dataclasses._DataclassParamsobjects, respectively. The field object
also adds anative_fieldattribute that is the original field object from the
underlying library.Examplefromdataclass_compatimportField,fieldsstandardized_fields=(Field(name="a",type=int,default=0),Field(name="b",type=str,default="b"),Field(name="c",type=list[int],default_factory=list),)assert(fields(SomeDataclass)==fields(SomePydanticModel)==fields(SomeAttrsModel)==fields(SomeMsgspecStruct)==standardized_fields)Supported librariesdataclassescollections.namedtuplepydantic(v1 and v2)attrsmsgspecdataclassysqlmodel(it's just pydantic)... maybe someday?pyfieldsmarshmallowsqlalchemydjangopeeweepyrsistentrecordclass
Package: dataclassconfig
dataclassconfigThe simplest interface for working with configuration files. Describe the structure of your configuration file as a dataclass. Use inheritance and composition to describe the complex hierarchical structure of a configuration file.InstallationpipinstalldataclassconfigRequirementsMinimum Python version supported bydataclassconfigis 3.6UsageDescribe the structure of your config file like adataclassand inherit it fromСonfigfromdataclassconfigimportConfigclassSocket(Config):host:strport:intclassDatabaseConnection(Socket):database:strusername:strpassword:strclassServerConfig(Config):root:strdb:DatabaseConnectionCreate a configuration file according to the described structure in YML or JSON format# server-config.ymlroot:~/serverdb:host:localhostport:1234database:databaseusername:demouserpassword:demopassword// server-config.json{"root":"~/server","db":{"host":"localhost","port":1234,"database":"database","username":"demouser","password":"demopassword",},}Load the config file using your classconfig=ServerConfig.load("server-config.yml")orconfig=ServerConfig.load("server-config.json")Theloadmethod will check the completeness of the provided data in the configuration file and strictly match the data types. The result will be the same in both cases, the config object contains fields defined in the classconfig:-ServerConfig(root='~/server',db=DatabaseConnection(host='localhost',port=1234,database='database',username='demouser',password='demopassword'))config.db.username:-'demouser'GratitudeThis module works thanks to the implementation in thedaciteprojectAuthorsCreated by Vladislav A. Proskurov
Package: dataclass-dateproperty
Weekdays and datetime properties for the dataclass_property library.Examplesimporttimeimportdatetimefromdataclass_propertyimportdataclass,field,fieldsfromdataclass_datepropertyimportdatetime_property,time_property,date_property,Weekdays,weekdays_propertynow=datetime.datetime.now()time.sleep(0.1)@dataclassclassAlarm:timer=datetime_property(default_factory=datetime.datetime.now)weekdays:Weekdays=field(default_factory=Weekdays(monday=True).copy)sunday:bool=weekdays_property('sunday')monday:bool=weekdays_property('monday')tuesday:bool=weekdays_property('tuesday')wednesday:bool=weekdays_property('wednesday')thursday:bool=weekdays_property('thursday')friday:bool=weekdays_property('friday')saturday:bool=weekdays_property('saturday')a=Alarm()fs=[f.nameforfinfields(a)]assert'timer'infs,fsassert'weekdays'infsassert'sunday'infsassert'monday'infsassert'tuesday'infsassert'wednesday'infsassert'thursday'infsassert'friday'infsassert'saturday'infsasserta.timer>nowasserta.weekdays.sundayisFalseasserta.weekdays.mondayisTrueasserta.weekdays.tuesdayisFalseasserta.sundayisFalseasserta.mondayisTrueasserta.tuesdayisFalsea=Alarm(timer=now,sunday=True)asserta.timer==nowasserta.weekdays.sundayisTrueasserta.weekdays.mondayisTrueasserta.weekdays.tuesdayisFalseasserta.sundayisTrueasserta.mondayisTrueasserta.tuesdayisFalse
Package: dataclass-deser
dataclass-deserA simple deserialization library for python based on dataclasses and type hints.I've written this code repeatedly across several of my scripts,
so I've decided to publish it to PyPi for reuse.Basic Example@dataclassclassNested:foo:int@dataclassclassFoo:bar:intbaz:list[int]nested:Nestedraw_json="""{"bar": 3,"baz": [1, 2, 8],"nested": {"foo": 42}}"""expected=Foo(bar=3,baz=[1,2,8],nested=Nested(foo=42))ctx=dataclass_deser.DeserContext()assertexpected==ctx.deser(Foo,json.loads(raw_json))StatusWARNING: This library isALPHA qUaLitYBasic primitive deserializationSupport lossless numeric conversions (int -> float)Support lossy numeric conversionSupport for optional typesSupport for union types (int | str | bytes)Configuration optionsAllow unused keysExtensibilityField options via dataclass field.metadataNewtype wrappersSupport more collectionsDictionariesTuplesSetsSupport enumerations
Package: dataclass-dict
dataclass_dictWith this package you are able to create a dataclass that works exactly like a dictionary.InstallThis packageonly works with python 3.6 or abovebecause it usesdataclasses. In python 3.6
it will uses the dataclass package from pypi.To use this package you may run the following command:pip install dataclass-dictHow to CollaborateIf you want to help with the development of this library, I would say that I love you but my
fiancee would get jealous, so I will just say thank you :DBy throwing money at the screenTidelif: We are on Tidelift! So you can get some technical support from them, and they help us.
It's a win win! If you are interested,click here(we get some help if you use this referal link too~)Patreon: If you want to help us every month, you can help us by checking our patreon pagehereKo-fi: Do you like Coffee, I love coffee, if you want to send a tip for a coffee, you can do
thathereBy providing help with codingFirst, make sure you haveat least Python 3.6, git and pip up and running:python -V
pip -V
git --versiondownload this repository with the following command using git:git clone https://github.com/Cerberus1746/dataclass_dict.gitAnd then cd into the directory with:cd dataclass_dictNow, if you want to just run the tests to test your changes, you can run:pip install tox
toxIf you want to generate docs, you can install all dependencies with:pip install .[docs]And then generate the docs with the command:python setup.py build_sphinxThe docs will be located by default inside the directorydocs/build/htmlSecurity contact informationTo report a security vulnerability, please use theTidelift security contact. Tidelift will coordinate the fix and
disclosure.
Package: dataclass-dict-convert
Dataclass Dict ConvertThis library converts between pythondataclassesand dicts (and json).It was created because when using thedataclasses-jsonlibrary for my use case, I ran into limitations and performance issues.
(There's alsotyped-json-dataclassbut I haven't evaluated that library.)Since creating this library, I've discoveredPydentic, which is a much more professional library, that in 99% of cases will be much more suitable than this library.
So I strongly recommend using Pydentic. If you usedataclass-dict-convert, beware that it is poorly maintained, not very well documented, may contain some bugs, and has some strange edge cases where it doesn't work.dataclass-dict-convertsupports lists, optionals, dicts, enums, nested dataclasses, etc.
It handles dates using RFC3339 (and enforces timezones and timezone awaredatetime).Example:fromdataclassesimportdataclassfromstringcaseimportcamelcasefromtypingimportOptional,Listfromdataclass_dict_convertimportdataclass_dict_convert@dataclass_dict_convert(dict_letter_case=camelcase)@dataclass(frozen=True)classTestB:an_int:inta_str:stra_float:floata_bool:bool@dataclass_dict_convert(dict_letter_case=camelcase)@dataclass(frozen=True)classTest:nestedClass:TestBnestedInOpt:Optional[TestB]nestedInList:List[TestB]the_instanceB1=TestB(1,'foo',0.1,True)the_instanceB2=TestB(2,'bar',0.2,False)the_instanceB3=TestB(3,'baz',0.3,True)the_instanceB4=TestB(4,'huh',0.4,False)the_instance=Test(the_instanceB1,the_instanceB2,[the_instanceB3,the_instanceB4])the_dict={'nestedClass':{'anInt':1,'aStr':'foo','aFloat':0.1,'aBool':True,},'nestedInOpt':{'anInt':2,'aStr':'bar','aFloat':0.2,'aBool':False,},'nestedInList':[{'anInt':3,'aStr':'baz','aFloat':0.3,'aBool':True,},{'anInt':4,'aStr':'huh','aFloat':0.4,'aBool':False,},],}expected=the_dictactual=the_instance.to_dict()assertactual==expectedexpected=the_instanceactual=Test.from_dict(the_dict)assertactual==expectedThe library also includes:RFC3339 tools (the default format for converting datetime to string),dataclass type checking toolsdataclass copy method generatordataclass multiline repr (replace auto generated repr for dataclasses by a multiline version)Links:Gitlab:https://gitlab.ilabt.imec.be/wvdemeer/dataclass-dict-convertPyPi:https://pypi.org/project/dataclass-dict-convert/
Package: dataclasses
This is an implementation of PEP 557, Data Classes.  It is a backport
for Python 3.6.  Because dataclasses will be included in Python 3.7,
any discussion of dataclass features should occur on the python-dev
mailing list athttps://mail.python.org/mailman/listinfo/python-dev.
At this point this repo should only be used for historical purposes
(it’s where the original dataclasses discussions took place) and for
discussion of the actual backport to Python 3.6.Seehttps://www.python.org/dev/peps/pep-0557/for the details of how
Data Classes work.A test file can be found athttps://github.com/ericvsmith/dataclasses/blob/master/test/test_dataclasses.py,
or in the sdist file.Installationpip install dataclassesExample Usagefromdataclassesimportdataclass@dataclassclassInventoryItem:name:strunit_price:floatquantity_on_hand:int=0deftotal_cost(self)->float:returnself.unit_price*self.quantity_on_handitem=InventoryItem('hammers',10.49,12)print(item.total_cost())Some additional tools can be found in dataclass_tools.py, included in
the sdist.CompatibilityThis backport assumes that dict objects retain their insertion order.
This is true in the language spec for Python 3.7 and greater.  Since
this is a backport to Python 3.6, it raises an interesting question:
does that guarantee apply to 3.6?  For CPython 3.6 it does.  As of the
time of this writing, it’s also true for all other Python
implementations that claim to be 3.6 compatible, of which there are
none.  Any new 3.6 implementations are expected to have ordered dicts.
See the analysis at the end of this email:https://mail.python.org/pipermail/python-dev/2017-December/151325.htmlAs of version 0.4, this code no longer works with Python 3.7. For 3.7,
use the built-in dataclasses module.Release HistoryVersionDateDescription0.82020-11-13Fix ClassVar in .replace()0.72019-10-20Require python 3.6 only0.62018-05-17Equivalent to Python 3.7.0rc10.52018-03-28Equivalent to Python 3.7.0b3
Package: dataclasses-configobj
dataclasses-configobjHydrate Data Classes fromini/dat/toml files.Aims to bedataclasses-json, but forconfigobj.This isvery alpharight now, but the feaures which work, should work:UsageDefine the shape of your config:Each subsection will be mapped to a nested classEach subsection may define a single_manyA_manymust have typeList[...]The type ofListof a_manyshall have a_nameExample:@dataclassclassSingle:other:str@dataclassclassOneOfMany:_name:strval:str@dataclassclassConfig:single:Single_many:List[OneOfMany]optional:Optional[str]=NoneTo load this.inifile:[single]
other = hello
[one]
val = apple
[two]
val = bananaWe can read, validate, andliftto an instance ofConfigwith:spec = core.to_spec(Config)
co = configobj.ConfigObj(infile=infile, configspec=spec)

validator = validate.Validator()
co.validate(validator)

config: Config = dataclasses.lift(Config, co)To yieldconfig:Config(
    single=Single(other='hello'),
    optional=None,
    withdefault='test123'
    _many=[
        OneOfMany(_name='one', val='apple'),
        OneOfMany(_name='two', val='banana')
    ]
)
Package: dataclassesdb
dataclassesdbGeneratesSQLandNoSQLdatabase models from @dataclassDocumentation:https://dutradda.github.io/dataclassesdbSource Code:https://github.com/dutradda/dataclassesdbKey FeaturesFast start data modeling with persistenceSupports from simple database schemas to complex oneIntegrate with:SQLALchemyaioredis(soon)google-datastore(soon)mongodb(planned)elasticsearch(planned)aws-dynamodb(planned)Same interface assqlalchemy.orm.session.SessionEasy integration with other data sourcesSupports redis data structure (like hashs, sets, etc) to store objectsRequirementsPython 3.7+Instalation$ pip install dataclassesdbBasic SQLAlchemy exampleimportasynciofromdataclassesdbimportDataSourceType,SessionFactoryfromdataclassesimportdataclass@dataclassclassMusic:name:str@dataclassclassPerson:name:strage:intmusic:Musicsession=SessionFactory.make(Music,Person,data_source=DataSourceType.RELATIONAL_SQLALCHEMY,data_source_args=dict(db_url='sqlite://',backrefs=True,create_tables=True,))person=Person(name='John',age=40,music=Music('Imagine'))session.add(person)# commit=True by defaultmusicQuery=session.query(Address)musics=musicQuery.filter(name='Imagine').all()loop=asyncio.get_event_loop()print(loop.run_until_complete(musics))[Music(name='Imagine',_id=1,backrefs=Backrefs(person=[Person(age=40,name=John,_id=1)]))]Basic aioredis with hash data type exampleimportasynciofromdataclassesdbimportDataSourceType,SessionFactoryAsyncfromdataclassesimportdataclass@dataclassclassMusic:name:str@dataclassclassPerson:name:strage:intmusic:Musicasyncdefget_musics():session=awaitSessionFactoryAsync.make(Address,Person,data_source=DataSourceType.MEMORY_AIOREDIS,data_source_args=dict(db_url='redis://',backrefs=True,))person=Person(name='John',age=40,music=Music('Imagine'))awaitsession.add(person)musicQuery=awaitsession.query(Address)returnawaitmusicQuery.filter(name='Imagine').all()loop=asyncio.get_event_loop()print(loop.run_until_complete(musics))[Music(name='Imagine',_id=1,backrefs=Backrefs(person=[Person(age=40,name=John,_id=1)]))]Basic aioredis with sorted set data type examplefromdataclassesdbimport(DataSourceType,MemorySortedSetRanked,ModelKey,SessionFactoryAsync,SortedValue,)fromdataclassesimportdataclass@dataclassclassMusic:id:ModelKey(str)name:strclassPlaylist(MemorySortedSetRanked):value_type=Music@dataclassclassPerson:name:strage:intplaylist:Playlistsession=awaitSessionFactoryAsync.make(Music,Playlist,Person,data_source=DataSourceType.MEMORY_AIOREDIS,data_source_args=dict(db_url='redis://',backrefs=True,))person=Person(name='John',age=40,playlist=Playlist(Music(id='imagine',name='Imagine'),Music(id='come-together',name='Come Together'),))awaitsession.add(person)playlistQuery=awaitsession.query(Playlist)playlist=awaitplaylistQuery.filter(Person.name=='John').one(withrank=True)print(playlist)[SortedValue(rank=1,key='imagine'),SortedValue(rank=2,key='come-together')]
Package: dataclasses-fromdict
dataclasses_fromdictUsagefromdataclassesimportdataclass,asdictfromdataclasses_fromdictimportfrom_dict@dataclassclassPoint:x:inty:intassertfrom_dict(asdict(Point(10,20)),Point)==Point(10,20)Supportgeneric listgeneric tuplegeneric var tuple
Package: dataclasses-sql
dataclasses-sqlUsing dataclasses with SQL databases.Examples:importdataclassesimportsqlalchemyimportdataclasses_sql@dataclasses.dataclassclassCar:brand:str=dataclasses.field(metadata={"key":True})model:str=dataclasses.field(metadata={"key":True})milage:float# Connect to databaseengine=sqlalchemy.create_engine("sqlite:///:memory:")metadata=sqlalchemy.MetaData(engine)metadata.reflect()# Insertcar=Car("Kia","Ceed",15678)dataclasses_sql.insert(metadata,car,check_exists=True)car=Car("Ford","Mustang",4032)dataclasses_sql.insert(metadata,car,check_exists=True)# Selectbuilder=dataclasses_sql.SelectStatementBuilder()builder.add_column(Car,"mileage")builder.add_clause(Car,"brand","Kia")statement=builder.build()withmetadata.bind.begin()asconn:row=conn.execute(statement).fetchone()print(row)InstallationEasiest way to install usingpip:pip install dataclasses-sqlFor development installation from the git repository::git clone git@github.com/ppinard/dataclasses-sql.git
cd dataclasses-sql
pip install -e .Release notes0.3Add delete function0.2Add update functionContributorsLicenseThe library is provided under the MIT license license.Copyright (c) 2020, Philippe Pinard
Package: dataclasses-sqlitedict
Welcome todataclasses_sqlitedictDocumentationSqlite backed dataclasses. It is a light weight persistent storage for dataclasses.
If you are looking for a full featured ORM, please check out SQLAlchemy.FeaturesSingle Row Data ModelEach instance of class is a row in the table. And all the instances of the same class share the same database table.importdataclassesfromsqlitedictimportSqliteDictfromdataclasses_sqlitedictimportSingleRowDataModel@dataclasses.dataclassclassUser(SingleRowDataModel):username:strpassword:strdb=SqliteDict("user.sqlite",autocommit=False)@propertydefprimary_key(self)->str:returnself.usernameuser=User(username="alice",password="pwd")user.write()user1=User.read("alice")print(user1)Single Table Data ModelEach instance of class is a table. Each instance of class could be different tables in the same databases, or different table in different databases.importdataclassesfromsqlitedictimportSqliteDictfromdataclasses_sqlitedictimportSingleTableDataModel@dataclasses.dataclassclassUser(SingleTableDataModel):username:strpassword:strdb=SqliteDict("user.sqlite",autocommit=False)user=User(db=db,username="alice",password="pwd")user.write()user1=User.read(db)print(user1)Installdataclasses_sqlitedictis released on PyPI, so all you need is:$pipinstalldataclasses_sqlitedictTo upgrade to latest version:$pipinstall--upgradedataclasses_sqlitedict
Package: dataclasses-ujson
Installpip install dataclasses_ujsonJSON with DataClassesThe library provides a simple API for decoding JSON to dataclasses.
You can use nested dataclasses. The library usesujsonfor better performance.
There is support for validate simply type: str, int, float, bool, Optional
Minimal python version: python 3.7ExamplesfromtypingimportList,Dictfromdataclassesimportdataclassfromdataclasses_ujson.dataclasses_ujsonimportUJsonMixinjson_string="""{"a": 1, "b": [{"x": 1}, {"x": 2}], "c": {"x": 1}}"""@dataclass(frozen=True)classJsonDict(UJsonMixin):x:Dict[str,int]@dataclass(frozen=True)classJsonClass(UJsonMixin):a:intb:List[JsonDict]c:Dict[str,int]data=JsonClass.loads(json_string)print(data.c["x"])print(list(data.b)[0].x)All lists will be returned as generatorsfromtypingimportList,Dictfromdataclassesimportdataclassfromdataclasses_ujson.dataclasses_ujsonimportUJsonMixinjson_string="""[{"x": 1}, {"x": 2}]"""@dataclass(frozen=True)classJsonDict(UJsonMixin):x:Dict[str,int]data=JsonDict.loads(json_string,many=True)print(data)# generator object UJsonMixinprint(list(data))# list of JsonDictPerformance:Libraries were compared:The default libraryjsonof pythonThe libraryujsonhttps://github.com/esnme/ultrajsonThe librarydataclasses-jsonhttps://github.com/lidatong/dataclasses-jsonThe script is placed in repository (bench_marks.py):Name of libraryResultsjson0.62sujson0.53sdataclasses-ujson1.24s(python3.10)dataclasses-json21.6sif generator will be returned (using flag many=true)Name of libraryResultsjson0.62sujson0.54sdataclasses-ujson0.59sdataclasses-json-
Package: dataclasses-xargs
dataclasses-xargsAn extension to the dataclasses library allowing you to push your unnamed parameters to a specific field.Installationpip3installdataclasses-xargsUsage Examplefromdataclasses_xargsimportdataclass@dataclassclassFailTest(object):a:int=Noneb:str=Nonec:list=None@dataclass(xarg_field="c")classSuccessTest(object):a:int=Noneb:str=Nonec:list=None# When xarg_field is not defined, dataclasses work as normal and will throw an error if you pass in double parameterstry:FailTest(1,2,3,4,5,a=1,b="b")exceptTypeErrorase:asserte.args[0]=="FailTest.__init__() got multiple values for argument 'a'"# When defined, and the xarg_field is not passed as a named parameter, all unnamed parameters will be pushed to the xarg_field.# Note that the xarg_field still needs to be defined in the class, see above.dcl=SuccessTest(1,2,3,4,5,a=1,b="b")print(dcl)"""SuccessTest(a=1, b='b', c=(1, 2, 3, 4, 5))"""assertdcl.a==1assertdcl.b=="b"assertdcl.c==(1,2,3,4,5)dcl=SuccessTest(1,2,3,4,5,a=1,b="b",c=[0,0,0])print(dcl)"""SuccessTest(a=1, b='b', c=[0, 0, 0])"""assertdcl.a==1assertdcl.b=="b"assertdcl.c==[0,0,0]exit(0)
Package: dataclass-factory
dataclass_factorydataclass_factoryis a modern way to convert dataclasses or other objects to and from more common types like dictsHelpSeedocumentationfor more details.TL;DRInstallpipinstalldataclass_factoryUsefromdataclassesimportdataclassimportdataclass_factory@dataclassclassBook:title:strprice:intauthor:str="Unknown author"data={"title":"Fahrenheit 451","price":100,}factory=dataclass_factory.Factory()book:Book=factory.load(data,Book)# Same as Book(title="Fahrenheit 451", price=100)serialized=factory.dump(book)Requirementspython >= 3.6You can usedataclass_factorywith python 3.6 anddataclasslibrary installed from pip.On python 3.7 it has no external dependencies outside of the Python standard library.AdvantagesNo schemas or configuration needed for simple cases. Just createFactoryand callload/dumpmethodsSpeed. It is up to 10 times faster thanmarshmallowanddataclasses.asdict(seebenchmarks)Automatic name style conversion (e.g.snake_casetoCamelCase)Automatic skipping of "internal use" fields (with leading underscore)Enums, typed dicts, tuples and lists are supported out of the boxUnions and Optionals are supported without need to define them in schemaGeneric dataclasses can be automatically parsed as wellCyclic-referenced structures (such as linked-lists or trees) also can be convertedValidators, custom parser steps are supported.Multiple schemas for single type can be provided to support different ways of parsing of the same type