![]() ![]() boardwalk, 550 ) Working with async/await (Python 3.5+) append ( thread ) > for thread in threads : > thread. Now use it: > from threading import Thread > from monopoly import Monopoly > monopoly = Monopoly () > threads = > for x in range ( 10 ): > thread = Thread ( target = lambda : monopoly. boardwalk_price = 500 def boardwalk ( self ): """threaded_cached_property is really nice for when no one waitsįor other people to finish their turn and rudely start rollingĭice and moving their pieces.""" sleep ( 1 ) self. Threaded_cached_property: from cached_property import threaded_cached_property class Monopoly ( object ): def _init_ ( self ): self. Unfortunately causes problems with the standard cached_property. What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which ![]() _dict_ > # request the boardwalk property again > monopoly. boardwalk 550 > # invalidate the cache > del monopoly. Let’s demonstrate how to force the cache to invalidate: > monopoly = Monopoly () > monopoly. Results of cached functions can be invalidated by outside forces. Why doesn’t the value of monopoly.boardwalk change? Because it’s a cached property! Invalidating the Cache Now when we run it the price stays at $550. Don't worry about it, this is # just an example for clarity. boardwalk_price = 500 def boardwalk ( self ): # Again, this is a silly example. from cached_property import cached_property class Monopoly ( object ): def _init_ ( self ): self. Let’s convert the boardwalk property into a cached_property. Now run it: > monopoly = Monopoly () > monopoly. boardwalk_price = 500 def boardwalk ( self ): # In reality, this might represent a database call or time # intensive task like calling a third-party API. Price goes up by $50! class Monopoly ( object ): def _init_ ( self ): self. Let’s define a class with an expensive property. I needed something really simple that worked in Python 2 and 3. Makes caching of time or computational expensive properties quick and easy.īecause I got tired of copy/pasting this code from non-web project to non-web project.
0 Comments
Leave a Reply. |