Skip to main content

Various tools for working with objects and classes in Python

Project description

Various tools for working with objects and classes in Python

Cached properties

Works just like a normal property, but returned values are cached:

from objecttools import CachedProperty

class ExpensiveOperations(object):
    @CachedProperty
    def expensive_attribute(self):
        return self.calculate()

    # To make it settable

    @expensive_attribute.setter
    def expensive_attribute(self, value):
        pass

    # To make it deletable

    @expensive_attribute.deleter
    def expensive_attribute(self):
        pass

e = ExpensiveOperations()
e.other_attribute = 1
print(e.expensive_attribute)  # Takes a long time.
print(e.expensive_attribute)  # Very quick; just retrieve from cache
v = e.expensive_attribute

e.other_attribute = 2  # expensive_attribute should be different now!
print(e.expensive_attribute)  # Old value that is wrong.
del e.expensive_attribute
print(e.expensive_attribute)  # Takes a long time, but returns new value.
e.other_attribute = 1
# Reset to known value
e.expensive_attribute = v
print(e.expensive_attribute)  # Correct value!

Singletons

from objecttools import Singleton

Sentinel = Singleton.create('Sentinel')

Sentinel() is Sentinel()  # True

d.get('missing_value', Sentinel()) is Sentinel()  # True

class GlobalState(dict, metaclass=Singleton):
    attr = 0


gs = GlobalState()
gs['value'] = 7
gs.attr = 1

print(GlobalState()['value'] + GlobalState().attr)  # 8

For Python 2 and 3 compatibility, use it as a decorator:

@Singleton.as_decorator
class Class(object):
    pass

Installing

From PyPI

$ pip install objecttools

From source

$ git clone 'https://github.com/MitalAshok/objecttools.git'
$ python ./objecttools/setup.py install

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

objecttools-0.0.6.zip (12.5 kB view details)

Uploaded Source

File details

Details for the file objecttools-0.0.6.zip.

File metadata

  • Download URL: objecttools-0.0.6.zip
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for objecttools-0.0.6.zip
Algorithm Hash digest
SHA256 10d9a720208ce94e5e55d93d9dbf5245da1e4ba142809ec1b3e3b6d7b78f028d
MD5 0a96f235b93ca6a25eb1e38d688cc03b
BLAKE2b-256 b01f23d9e259991107267c5146cc30b56dfb38c1c01d8584229166a149fb1c32

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page