Skip to content Navigation Menu Toggle navigation Sign in Appearance settings PlatformAI CODE CREATIONGitHub CopilotWrite better code with AIGitHub Copilot appDirect agents from issue to mergeMCP RegistryNewIntegrate external toolsDEVELOPER WORKFLOWSActionsAutomate any workflowCodespacesInstant dev environmentsIssuesPlan and track workCode ReviewManage code changesAPPLICATION SECURITYGitHub Advanced SecurityFind and fix vulnerabilitiesCode securitySecure your code as you buildSecret protectionStop leaks before they startEXPLOREWhy GitHubDocumentationBlogChangelogMarketplaceView all featuresSolutionsBY COMPANY SIZEEnterprisesSmall and medium teamsStartupsNonprofitsBY USE CASEApp ModernizationDevSecOpsDevOpsCI/CDView all use casesBY INDUSTRYHealthcareFinancial servicesManufacturingGovernmentView all industriesView all solutionsResourcesEXPLORE BY TOPICAISoftware DevelopmentDevOpsSecurityView all topicsEXPLORE BY TYPECustomer storiesEvents & webinarsEbooks & reportsBusiness insightsGitHub SkillsSUPPORT & SERVICESDocumentationCustomer supportCommunity forumTrust centerPartnersView all resourcesOpen SourceCOMMUNITYGitHub SponsorsFund open source developersPROGRAMSSecurity LabMaintainer CommunityAcceleratorGitHub StarsArchive ProgramREPOSITORIESTopicsTrendingCollectionsEnterpriseENTERPRISE SOLUTIONSEnterprise platformAI-powered developer platformAVAILABLE ADD-ONSGitHub Advanced SecurityEnterprise-grade security featuresCopilot for BusinessEnterprise-grade AI featuresPremium SupportEnterprise-grade 24/7 supportPricing Search or jump to... Search code, repositories, users, issues, pull requests... Search Clear Search syntax tips Provide feedback We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Saved searches Use saved searches to filter your results more quickly Name Query To see all available qualifiers, see our documentation. Sign in Sign up Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} twtrubiks / python-notes Public Notifications You must be signed in to change notification settings Fork 52 Star 109 Code Issues 0 Pull requests 0 Actions Projects Security and quality 0 Insights Additional navigation options Code Issues Pull requests Actions Projects Security and quality Insights FilesExpand file tree masterBreadcrumbspython-notes/cachetools_tutorial.pyCopy pathBlameMore file actionsBlameMore file actions Latest commit HistoryHistoryHistory94 lines (70 loc) · 1.61 KB masterBreadcrumbspython-notes/cachetools_tutorial.pyCopy pathTopFile metadata and controlsCodeBlame94 lines (70 loc) · 1.61 KBRawCopy raw fileDownload raw fileOpen symbols panelEdit and raw actions12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""pip3 install cachetools https://pypi.org/project/cachetools/""" from cachetools import cached, LRUCache, TTLCacheimport time @cached(cache={})def ex1_cache(): print('no cached') return 'my data' def ex1(): for _ in range(3): print(ex1_cache()) # 手動清理快取 # ex1_cache.cache_clear() # for _ in range(3): # print(ex1_cache()) @cached(LRUCache(maxsize=10))def ex2_cache(count): print('no cached') return 'my data' def ex2(): print('step1...') for i in range(10): # 這裡沒快取 因為第一次 print(ex2_cache(i)) print('step2...') for i in range(10): # 這裡都有快取 print(ex2_cache(i)) print('step3...') for i in range(30, 40): # 快取開始失效, 因為超過 maxsize print(ex2_cache(i)) @cached(TTLCache(maxsize=5, ttl=2))def ex3_cache(): print('no cached') return 'my data' def ex3(): for _ in range(5): print(ex3_cache()) time.sleep(3) # 快取失效 for _ in range(5): print(ex3_cache()) MY_CACHE = TTLCache(maxsize=200, ttl=2) def set_cache(): MY_CACHE['1'] = '1' MY_CACHE['2'] = '2' MY_CACHE['3'] = '3' def get_cache(): if MY_CACHE.get('1'): print('cached') print(MY_CACHE.get('1')) else: print('no cached') def ex4(): set_cache() for _ in range(3): get_cache() print('查看目前 cache 狀態:', dict(MY_CACHE)) print('sleep 2.5 sec') time.sleep(2.5) # cached expired get_cache() if __name__ == '__main__': ex1() # ex2() # ex3() # ex4() You can’t perform that action at this time.