Saravanan666/pypi-org huggingface dataset:
Package: cachetools-chrisglass
This module provides various memoizing collections and decorators,
including variants of the Python Standard Library’s@lru_cachefunction decorator.fromcachetoolsimportcached,LRUCache,TTLCache# speed up calculating Fibonacci numbers with dynamic programming@cached(cache={})deffib(n):returnnifn<2elsefib(n-1)+fib(n-2)# cache least recently used Python Enhancement Proposals@cached(cache=LRUCache(maxsize=32))defget_pep(num):url='http://www.python.org/dev/peps/pep-%04d/'%numwithurllib.request.urlopen(url)ass:returns.read()# cache weather data for no longer than ten minutes@cached(cache=TTLCache(maxsize=1024,ttl=600))defget_weather(place):returnowm.weather_at_place(place).get_weather()For the purpose of this module, acacheis amutablemappingof a
fixed maximum size.  When the cache is full, i.e. by adding another
item the cache would exceed its maximum size, the cache must choose
which item(s) to discard based on a suitablecache algorithm.  In
general, a cache’s size is the total size of its items, and an item’s
size is a property or function of its value, e.g. the result ofsys.getsizeof(value).  For the trivial but common case that each
item counts as1, a cache’s size is equal to the number of its
items, orlen(cache).Multiple cache classes based on different caching algorithms are
implemented, and decorators for easily memoizing function and method
calls are provided, too.Installationcachetools is available fromPyPIand can be installed by running:pip install cachetoolsTyping stubs for this package are provided bytypeshedand can be
installed by running:pip install types-cachetoolsProject ResourcesDocumentationIssue trackerSource codeChange logLicenseCopyright (c) 2014-2021 Thomas Kemmer.Licensed under theMIT License.
Package: cachetoolz
Cache ToolzThis library offers a decorator that enhances the functionality of caching functions.Caching is a technique commonly used in software development to improve performance by storing the results of expensive or time-consuming function calls. With this library, you can easily apply caching to your functions using a decorator.The decorator provided by this library automatically checks if the function has been called with the same set of arguments before. If it has, instead of executing the function again, it returns the cached result, saving valuable processing time. However, if the function is called with new or different arguments, it will execute normally and cache the result for future use.By incorporating this caching decorator into your code, you can optimize the execution of functions that involve complex computations, database queries, API calls, or any other operations that could benefit from caching.Overall, this library simplifies the implementation of caching in your applications, allowing you to enhance performance and reduce resource consumption effectively.InstallationInstall and update usingpip:pip install cachetoolzA Examplefromdataclassesimportasdict,dataclass,fieldfromdatetimeimporttimedeltafromuuidimportUUID,uuid4fromcachetoolzimportcachefromcachetoolz.coderimportcoderTODOS:list['Todo']=[]@dataclassclassTodo:title:strstatus:bool=field(default=False,compare=False)id:UUID=field(default_factory=uuid4,compare=False)# Registering an object coder@coder.registerclassTodoSerializer:defencode(self,value:Todo):# Need type annotatedreturnasdict(value)defdecode(self,value):returnTodo(**value)# Adding cache to function with expiry time in seconds@cache(ttl=120,namespace='todo')defget_one(id:UUID):returnnext(filter(lambdatodo:todo.id==id,TODOS),None)# Adding expiry time using timedelta@cache(ttl=timedelta(minutes=30),namespace='todo')defget_all():returnTODOS# Clear all caches on given namesoaces@cache.clear(namespaces=['todo'])defadd_one(title,status=False):if(todo:=Todo(title=title,status=status))notinTODOS:TODOS.append(todo)
Package: cachetory
CachetoryDocumentationSneak peakfromcachetoryimportserializersfromcachetory.backendsimportasync_asasync_backendsfromcachetory.caches.async_importCachecache=Cache[int,bytes](serializer=serializers.from_url("pickle://?pickle-protocol=4"),backend=async_backends.from_url("redis://localhost:6379"),)asyncdefmain()->None:awaitcache.set("foo",42)assertawaitcache.get("foo")==42
Package: cachext
# [Home Page](https://shanbay.github.io/cachext/)[![](https://img.shields.io/travis/shanbay/cachext.svg?style=flat-square)](https://travis-ci.org/shanbay/cachext)
[![Maintainability](https://api.codeclimate.com/v1/badges/774db211d37720bb2599/maintainability)](https://codeclimate.com/github/shanbay/cachext/maintainability)
[![Coverage Status](https://coveralls.io/repos/github/shanbay/cachext/badge.svg?branch=master)](https://coveralls.io/github/shanbay/cachext?branch=master)
[![](https://img.shields.io/pypi/v/cachext.svg)](https://github.com/shanbay/cachext)
[![](https://img.shields.io/pypi/pyversions/cachext.svg)](https://github.com/shanbay/cachext)
[![](https://img.shields.io/:license-mit-blue.svg?style=flat-square)](https://shanbay.mit-license.org)
Package: cachey
Caching for Analytic ComputationsHumans repeat stuff.  Caching helps.Normal caching policies like LRU aren't well suited for analytic computations
where both the cost of recomputation and the cost of storage routinely vary by
one million or more.  Consider the following computations# Want thisnp.std(x)# tiny result, costly to recompute# Don't want thisnp.transpose(x)# huge result, cheap to recomputeCachey tries to hold on to values that have the following characteristicsExpensive to recompute (in seconds)Cheap to store (in bytes)Frequently usedRecenty usedIt accomplishes this by adding the following to each items score on each accessscore += compute_time / num_bytes * (1 + eps) ** tick_timeFor some small value of epsilon (which determines the memory halflife.) This
has units of inverse bandwidth, has exponential decay of old results and
roughly linear amplification of repeated results.Example>>>fromcacheyimportCache>>>c=Cache(1e9,1)# 1 GB, cut off anything with cost 1 or less>>>c.put('x','some value',cost=3)>>>c.put('y','other value',cost=2)>>>c.get('x')'some value'This also has amemoizemethod>>>memo_f=c.memoize(f)StatusCachey is new and not robust.
Package: cacheyou
CacheYouCacheYou is a fork ofCacheControlwhich is a port of the caching algorithms in httplib2 for use with
requests session object.QuickstartimportrequestsfromcacheyouimportCacheControlsess=requests.session()cached_sess=CacheControl(sess)response=cached_sess.get('http://google.com')If the URL contains any caching based headers, it will cache the
result in a simple dictionary.For more info, check out thedocs
Package: cachez
VERSION: 0.1.2IntroductionFunction decorator that helps to cache/memoize the result of a function/method.This package contains following decorators.cache: cache the result of the function globally.instance_cache: cache the result of a method in the instance (self)clear_instance_cache: clear the method results cached on the instance.And one function.clear_cache: clear the global function cache.Tested on python 2.7 and python 3.4.For quick start, check the tutorial section of this page.
Checkcachez_test.pyfor detail examples.Installationpip install cachezLicenseApache License version 2TutorialTo cache the result of the a function globally, decorate the function
withcache.@cachedeffoo(x,y):...To clear the global cache, callclear_cache().clear_cache()To cache the result of the method in the instance, decorate the method
withinstance_cache.
To clear the method cache on the instance, decorate your clear method
withclear_instance_cache.classFoo(object):@instance_cachedefbar(a,b):...@clear_instance_cachedefclear():...To persist the function return value, usepersisteddecorator.
This decorator takes input parameter which specify when the cache
will expire.  The default value for cache expiration is set to 1 day.classFoo(object):@persisted()defdefault_persist_for_1_day(x):...@persisted(seconds=5)defpersist_return_value_for_5_seconds(y):...The default persist folder is set to~/.cachez.  You could customize
it by callingset_persist_folder.To file issue, please visit:https://github.com/jealous/cachezContact author:Cedric Zhuang <jealous@163.com>Contributors:Ryan Liang <menglei.leung@gmail.com>
Package: cachian
Basic UsageThis module provides memoization with LRU, TTL and various clearing utility functions.from cachian import Cachian

class PatientDB:

    @Cachian() #LRU caching defaulting to 10,000 items
    def get_by_id(self, id):
        pass

    @Cachian(maxsize=100) #LRU caching with 100 items
    def get_by_id2(self, id):
        pass        

    @Cachian(ttl=60) #TTL caching with TTL at 60 secs
    def get_latest_10_patient(self):
        pass
    
    #Split cache clearing by first args ie. id
    @Cachian(partition_attr=1)
    def get_by_id3(self, id):
        pass

    #TTL, LRU & partition caching, whichever miss first
    @Cachian(maxsize=100,ttl=60,partition_attr=1)
    def get_by_id4(self,id):
        pass


#Can be used with standalone functions
@Cachian()
def count_patient_name_len(patient_name):
    return len(patient_name)BackendsBy default, memory backend is used. Any class that subclasses MutableMapping can be used as a backend store. Refer to the default MemoryStore for a skeletal example.Using Redis as a backend can be achieved using:import os
os.environ["CACHIAN_REDIS_HOST"] = "prod.redis.com"
os.environ["CACHIAN_REDIS_PORT"] = "6380"
os.environ["CACHIAN_REDIS_DB"] = "8"
os.environ["CACHIAN_REDIS_SSL"] = "true"
os.environ["CACHIAN_REDIS_PASSWORD"] = "abc123"

from cachian.redis_store import RedisStore

class PatientDB:

    @Cachian(cache_class=RedisStore) #LRU caching defaulting to 10,000 items with Redis storage backend
    def get_by_id(self, id):
        passUtilitiesGet statsUtilities to obtain statistics on cached methods/functions. Code continues from theBasic Usageexample.from cachian import global_cache_info
from pprint import pprint

#Print stats of all cached function/methods
pprint(global_cache_info())

#Print stats of a single cached function/method
pprint(count_patient_name_len.cache_info())Clearing cacheA few clearing utilities to allow selecting clearing of cached items. Code continues from theBasic Usageexample.from cachian import function_cache_reset_by_class, function_cache_reset, global_cache_reset

#Clear all cached items of all methods in the class
function_cache_reset_by_class(PatientDB)

#Clear cache of a function
function_cache_reset('count_patient_name_len')

#Clear all cached items
global_cache_reset()InstallationBasic installationpip install CachianClone the repository to run unittests.Installing thecachetoolspackage will allow unittest to run benchmarks against cachetools.pip install cachetools
python -m unittest discover -s . -p "*_test.py"LicenseCopyright (c) 2023-2025 Ian TeohLicensed under theMITlicense
Package: cachier-client
Cachier Python ClientA template of README best practices to make your README simple to understand and easy to use.Table of ContentsInstallationUsageSupportContributingInstallationInstall the package using pip:pipinstallcachier_clientUsagefromcachier_clientimportCachierClientclient=CachierClient("localhost",8080).connect()print("should be None:",client.get("greetings"))client.set("greetings","Hello, World!",10)print("should be something:",client.get("greetings"))importtimetime.sleep(11)print("should be None:",client.get("greetings"))SupportPleaseopen an issuefor support.ContributingPlease contribute usingGithub Flow. Create a branch, add commits, andopen a pull request.
Package: cachier-common-library
Cachier Common LibraryA python library for common classes and functions used to build cachier applicationsTable of ContentsInstallationUsageSupportContributingInstallationInstall the package from pypi:pipinstallcachier-common-libraryUsagefromcachier_common_libraryimportDriverType# Using the DriverType enumprint(DriverType.RAM)print(DriverType.JSON)print(DriverType.SQLITE)print(DriverType.PICKLE)SupportPleaseopen an issuefor support.ContributingPlease contribute usingGithub Flow. Create a branch, add commits, andopen a pull request. -->
Package: cachier-python
Cachier PythonA python library wrapper for using a self-hosted cachier service.URL:cachier-pythonTable of ContentsInstallationUsageSupportContributingInstallationInstall the package from pypi:pipinstallcachier-pythonUsagefromcachier_pythonimportCachier,DriverType# Create a cachier instance to connect to the serviceclient=Cachier('http://localhost:8000',driver=DriverType.RAM)# cache expiry in secondsCACHIER_EXPIRY=600# set the cacheclient.set(key='my_key',value='my_value',expiry=CACHIER_EXPIRY)# get the cached valuecached_value=client.get(key='my_key')Available drivers:fromcachier_pythonimportDriverTypeDriverType.RAMDriverType.JSONDriverType.SQLITEDriverType.PICKLEcheck if a driver is valid:fromcachier_pythonimportDriverTypeis_valid=DriverType().is_valid(DriverType.RAM)print(is_valid)SupportPleaseopen an issuefor support.ContributingPlease contribute usingGithub Flow. Create a branch, add commits, andopen a pull request. -->
Package: caching
StatusWORK IN PROGRESSCachingPython utils and decorators for cаching with TTL, maxsize and file-based storage.Installationpip install cachingUsagefromcachingimportCache# File-based cache with unlimited ttl and maximum of 128 cached results@Cache(ttl=-1,maxsize=128,filepath='/tmp/mycache')deflong_running_function(a,b,*args,c=None,**kwargs):pass# Memory-based cache with limited ttl and maxsize and "least recently used"# cache replacement policy.@Cache(ttl=60,maxsize=128,policy='LRU')deflong_running_function(a,b,*args,c=None,**kwargs):passAdvanced usagefromcachingimportCache# One cache for many functionscache=Cache(filepath='/tmp/mycache',ttl=3600,maxsize=1024)@cachedefpow(x,y):returnx**y@cachedeffactorial(n):ifn==0:return1returnn*factorial(n-1)# Caching the last result and returning it only in case of errors@Cache(maxsize=1,only_on_errors=(ConnectionError,TimeoutError))defapi_request():"""Request some remote resource which sometimes become unavailable.
    If this functions raises ConnectionError or TimeoutError, then the
    last cached result will be returned, if available."""# Custom cache key function@Cache(key=lambdax:x[0])deftoupper(a):globalcall_countcall_count+=1returnstr(a).upper()call_count=0# The key function returns the same result for both 'aaa' and 'azz'# so the cached result from the first call is returned in the second callasserttoupper('aaa')==toupper('azz')=='AAA'assertcall_count==1# Using cache as a key-value storecache=Cache()try:result=cache[1]exceptKeyError:result=calculate_result(1)cache[1]=resultassert1incacheassertcache[1]==resultassertcache.get(1,None)==resultassertcache.get(2,None)isNone# Cleanupimportoscache=Cache(filepath='/tmp/mycache')cache[1]='one'assert1incachecache.clear()# empty the cacheassert1notincacheassertlist(cache.items())==[]assertos.path.isfile('/tmp/mycache')cache.remove()# Empty the cache and remove the underlying fileassertnotos.path.isfile('/tmp/mycache')Features[x] Memory and file based cache.[x] TTL and maxsize.[x] Works with*args,**kwargs.[x] Works with mutable function arguments of the following types:dict,list,set.[x] FIFO, LRU and LFU cache replacement policies.[x] Customizable cache key function.[ ] Multiprocessing- and thread-safe.[ ] Pluggable external caching backends (see Redis example).
Package: caching-py35
StatusWORK IN PROGRESSCachingPython utils and decorators for cаching with TTL, maxsize and file-based storage.Installationpip install cachingUsagefromcachingimportCache# File-based cache with unlimited ttl and maximum of 128 cached results@Cache(ttl=-1,maxsize=128,filepath='/tmp/mycache')deflong_running_function(a,b,*args,c=None,**kwargs):pass# Memory-based cache with limited ttl and maxsize and "least recently used"# cache replacement policy.@Cache(ttl=60,maxsize=128,policy='LRU')deflong_running_function(a,b,*args,c=None,**kwargs):passAdvanced usagefromcachingimportCache# One cache for many functionscache=Cache(filepath='/tmp/mycache',ttl=3600,maxsize=1024)@cachedefpow(x,y):returnx**y@cachedeffactorial(n):ifn==0:return1returnn*factorial(n-1)# Caching the last result and returning it only in case of errors@Cache(maxsize=1,only_on_errors=(ConnectionError,TimeoutError))defapi_request():"""Request some remote resource which sometimes become unavailable.
    If this functions raises ConnectionError or TimeoutError, then the
    last cached result will be returned, if available."""# Custom cache key function@Cache(key=lambdax:x[0])deftoupper(a):globalcall_countcall_count+=1returnstr(a).upper()call_count=0# The key function returns the same result for both 'aaa' and 'azz'# so the cached result from the first call is returned in the second callasserttoupper('aaa')==toupper('azz')=='AAA'assertcall_count==1# Using cache as a key-value storecache=Cache()try:result=cache[1]exceptKeyError:result=calculate_result(1)cache[1]=resultassert1incacheassertcache[1]==resultassertcache.get(1,None)==resultassertcache.get(2,None)isNone# Cleanupimportoscache=Cache(filepath='/tmp/mycache')cache[1]='one'assert1incachecache.clear()# empty the cacheassert1notincacheassertlist(cache.items())==[]assertos.path.isfile('/tmp/mycache')cache.remove()# Empty the cache and remove the underlying fileassertnotos.path.isfile('/tmp/mycache')Features[x] Memory and file based cache.[x] TTL and maxsize.[x] Works with*args,**kwargs.[x] Works with mutable function arguments of the following types:dict,list,set.[x] FIFO, LRU and LFU cache replacement policies.[x] Customizable cache key function.[ ] Multiprocessing- and thread-safe.[ ] Pluggable external caching backends (see Redis example).
Package: cachingutil
A hierarchy of classes to provide caching functionality
with minimal fuss.When using the cache, just use the fetch method.
This will pull from the cache if it’s present and
not expired otherwise will use ‘fetch_from_source’.CacheAbstract class.
Not expected to be used. Provides the methods
needed by subclasses provided by the package.Methods that need to be implemented in the concrete class:key
fetch_from_source
cache
fetch_from_cache_by_key
delete_by_key
expiry_timeOptional:cookBaseMemoryClassAbstract class.Methods that must be implemented in concrete class:key
fetch_from_source
calculate_expiryOptional:cookSimpleMemoryClassAbstract class.Methods that must be implemented in concrete class:key
fetch_from_sourceOptinal:cookBaseHttpMemoryCacheAbstract class.Caches requests objects or objects generated from requests.TODO: Improve expiry calculations. Currently only uses max age.Methods that must be implemented in concrete class:key
fetch_from_source
get_request_for_item (if caching objects generated from request objects)Optinal:cookHttpMemoryCacheConcrete class.Uses the url string as the key.
Uses requests.get as fetch_from_source.Use:
Instantiate and use instance.fetch(url) to fetch from the cache or source.BinaryFileCacheAbstract class.Reads from and writes to binary files. Suitable for caching
images.Methods that must be implemented in concrete class:key
fetch_from_sourceOptional:cookFileCacheAbstract class.Reads from and writes to files with encoding.Methods that must be implemented in concrete class:key
fetch_from_sourceOptional:cook
encode
decodeJsonFileCacheAbstract class.This is just FileCache with JSON encoding and decoding.fetch_from_source should return a JSON string.
If OBJECT_PAIRS_HOOK is set, then decode will
use that. Typically use: collections.OrderedDict
to retain the order of elements.Methods that must be implemented in concrete class:key
fetch_from_sourceOptional:cook
OBJECT_PAIRS_HOOKTwoLevelCacheConcrete class.Generally this means an in-memory cache joined to a
persistent cache (e.g, file, database). That means
your cache persists over many executions, but doesn’t
need to access the slower persistent cache more than
once per item fetched.To use it, implement the two caches and instantiate
TwoLevelCache to join them. Pass in-memory cache class
as the transient_cache and the persistent cache class
as (surprise!) the pesistent_cache.
Package: cachingutils
cachingutilsUtilities to make caching data easierExamplesBasic caching:fromcachingutilsimportcached@cached()deffib(n:int)->int:ifn<2:returnnreturnfib(n-1)+fib(n-2)print(fib(100))# 354224848179261915075Caching with your own cache object:fromcachingutilsimportCache,cachedmy_cache=Cache()@cached(cache=my_cache)deffib(n:int)->int:ifn<2:returnnreturnfib(n-1)+fib(n-2)print(fib(100))# 354224848179261915075Caching with an LRU cache:fromcachingutilsimportLRUCache,cached@cached(cache=LRUCache(2,timeout=60),include_posargs=[0])deffetch_thing(thing_id:int,thing_name:str)->tuple[int,str]:returnthing_id,thing_name# Imagine this is a call to an APIprint(fetch_thing(123,"456"))# (123, "456")print(fetch_thing(123,"789"))# (123, "456")fetch_thing(567,"789")fetch_thing(789,"456")print(fetch_thing(123,"456"))# Cache missAsync caching:fromasyncioimportrunfromcachingutilsimportacached@acached()asyncdeffib(n:int)->int:ifn<2:returnnreturnawaitfib(n-1)+awaitfib(n-2)print(run(fib(100)))# 354224848179261915075Caching specific positional args:fromcachingutilsimportcached@cached(include_posargs=[0])asyncdefadd(a:int,b:int)->int:returna+bprint(add(1,2))# 3print(add(2,2))# 3print(add(2,3))# 5Caching specific keyword args:fromcachingutilsimportcached@cached(include_posargs=[0],include_kwargs=['c'])defadd(a:int,b:int,*,c:int)->int:returna+bprint(add(1,2,c=3))# 3print(add(2,2,c=3))# 4print(add(2,3,c=3))# 4Caching with a timeout:fromtimeimportsleepfromcachingutilsimportcached@cached(timeout=1,include_posargs=[0])defadd(a:int,b:int)->int:returna+bprint(add(1,2))# 3print(add(1,3))# 3sleep(2)print(add(1,3))# 4Using a rawCacheobject:fromtimeimportsleepfromcachingutilsimportCachemy_cache:Cache[str,int]=Cache(timeout=5)my_cache["abc"]=123print(my_cache["abc"])# 123sleep(6)print(my_cache["abc"])# KeyError: 'abc'All of the above decorators also work within classes:fromcachingutilsimportcachedclassMyClass:@cached()deffib(self,n:int)->int:ifn<2:returnnreturnself.fib(n-1)+self.fib(n-2)my_class=MyClass()print(my_class.fib(100))# 354224848179261915075
Package: cacho
CACHOA tiny C++ in-memory cache system with Least recently Used algorithm as a python shared-object library !How to installTo install the pyhon lib, just hit :pip3installcachoHow to use itimportcachoasc# To set a valuec.set("key1","value1")# We can also check if the key existifc.exists("key1"):# And get itprint(c.get("key1"))To build and deploy the lib on pypiYou just have to run these bash files :# cmake buildsh./shells/build.sh# building the wheelsh./shells/build_whl.sh# And to deploy on Pypi :sh./shells/pypi_deploy.shLICENSEMIT