Skip to content

Commit

Permalink
Optimize cython cached_property implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed Sep 7, 2024
1 parent 67c2c02 commit 0b9eb7f
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions yarl/_helpers_c.pyx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# cython: language_level=3

cdef _sentinel = object()

cdef class cached_property:
"""Use as a class method decorator. It operates almost exactly like
the Python `@property` decorator, but it puts the result of the
Expand All @@ -21,17 +23,14 @@ cdef class cached_property:
return self.wrapped.__doc__

def __get__(self, inst, owner):
try:
try:
return inst._cache[self.name]
except KeyError:
val = self.wrapped(inst)
inst._cache[self.name] = val
return val
except AttributeError:
if inst is None:
return self
raise
if inst is None:
return self
cdef dict cache = inst._cache
val = cache.get(self.name, _sentinel)
if val is _sentinel:
val = self.wrapped(inst)
cache[self.name] = val
return val

def __set__(self, inst, value):
raise AttributeError("cached property is read-only")

0 comments on commit 0b9eb7f

Please sign in to comment.