Skip to main content

Freezable mixin class

Project description

Freezable: Freezable objects in Python

NOTICE: This project is in Alpha. Code may be unstable. API is subject to change.

This Python package provides a mixin class to implement "freezable" objects. When an object is frozen, the data contained within the object is marked as immutable.

Installation

pip install freezable

Basic Usage

freezable provides the Freezable mixin class for user-defined objects:

from freezable import Freezable

class SomeFreezable(Freezable):
    ...

You do not need to call init for this class; you only need to subclass it, even in multiple inheritance.

To freeze an freezable object, use the freeze() method, and to unfreeze, use the unfreeze() method. You can check if a freezable object is frozen using the is_frozen() method.

obj = SomeFreezable()

assert not obj.is_frozen()

obj.freeze()
assert obj.is_frozen()

obj.unfreeze()
assert not obj.is_frozen()

While an object is frozen, setting and deleting attributes of that object is disabled; these operations raise a FrozenError while it is frozen.

obj = SomeFreezable()
obj.freeze()

# Both of these operations will raise a FrozenError:
obj.attr = 5
del obj.attr

If you don't want this behavior, you can override the special methods in the class body:

__setattr__ = object.__setattr__
__delattr__ = object.__delattr__

The package also provides the @enabled_when_unfrozen instance method decorator only enables a method if the object is unfrozen; when it is frozen, it raises a FrozenError. Make sure to only use this decorator in a class that subclasses Freezable.

class SomeFreezable(Freezable):
    @enabled_when_unfrozen
    def some_mutating_method(self):
        ...

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

freezable-0.1.2.tar.gz (3.8 kB view hashes)

Uploaded Source

Built Distribution

freezable-0.1.2-py3-none-any.whl (3.8 kB view hashes)

Uploaded Python 3

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