qtils.properties module¶
See more usage examples in Property decorators
-
qtils.properties.
weakproperty
(setter)¶ Returns a property that stores values as
weakref.Ref()
The weakref object is stored as
'_' + setter.__name__
Parameters: setter (function) – setter function (can be an empty function) Returns: returns property instance Example
>>> import sys >>> class SomeClass(object): pass >>> class Foo(object): ... @weakproperty ... def bar(self, value): pass ... >>> some_obj = SomeClass() >>> original_refcount = sys.getrefcount(some_obj) >>> foo = Foo() >>> foo.bar = some_obj # Reference count should not increase because some_obj is weak referenced. >>> original_refcount == sys.getrefcount(some_obj) True >>> foo._bar # weakref object stored as private variable <weakref at ... to 'SomeClass' at ...> >>> foo.bar <qtils.properties.SomeClass object at ...> >>> foo.bar == some_obj True
-
qtils.properties.
cachedproperty
(getter=None, setter=None, deleter=None, varname=None)¶ Returns a property that caches first return of getter until a del is called.
Parameters: - getter (function) – Getter function
- setter (function) – Setter function
- deleter (function) – Deleter function
- varname (str) – Variable name to store cached data at, defaults to
getter.__name__
Returns: property object with caching ability
Return type: return (property)
Example
Tyical usage:
>>> class Foo(object): ... @cachedproperty ... def bar(self): ... # doing some super computation-intensive thing here ... print('getter called') ... return "hello world" ... >>> obj = Foo() >>> obj.bar # first call, getter is called getter called 'hello world' >>> obj.bar # second call, getter is not called 'hello world' >>> obj._bar # data is stored under '_'+setter.__name__ 'hello world' >>> del obj.bar # removing cached value >>> obj.bar # getter is called again getter called 'hello world' >>> del obj.bar >>> obj.bar = 'ni!' # value can also be set from the outside >>> obj.bar # no getter will be called 'ni!'
Using a different variable to cache data:
>>> class Foo(object): ... @cachedproperty(varname='_some_var') ... def bar(self): ... return "result of intensive calculation" >>> obj = Foo() >>> obj.bar 'result of intensive calculation' >>> obj._some_var # cached data will be stored under custom name 'result of intensive calculation'