Skip to main content

Makes read only attributes for a Python class

Project description

Read Only Attributes

Build Status codecov Code style: black

Info:

This package makes class attributes read only.

Motivation:

We can make read only attributes using @property. But this can be verbose. Worse, the intent is not clear as in these attributes are meant to be read-only.

Like as below

    class MyClass:
        @property
        def x(self):
            return 'immutable 1'
        @property
        def y(self):
            return 'immutable 2'
        @property
        def z(self):
            return 'immutable 3'
        @property
        def w(self):
            return 'immutable '

The above can be written like so which is much less verbose and lot more explicit:

@read_only_attributes('x','y','z','w')
class MyClass:
    def __init__(self, x, y, z, w):
        self.x = x 
        self.y = y 
        self.z = z 
        self.w = w 

Once the instance attributes are assigned in the _init_, they cannot be changed. Trying to change them will raise an AttributeError.

Installation:

pipenv install read-only-properties

Usage:

import class decorator @read_only_attributes and use like so:

from roa import read_only_attributes

@read_only_attributes('x', 'y')
class MyClass:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

That's it. There us no need to use @property.
'x' and 'y' are now readonly attributes. If we try to change them, AttributeError exception will be raised.
Since 'z' is not in decorator argument list, self.z is a mutable instance attribute.

Project details


Download files

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

Files for read-only-attributes, version 1.2
Filename, size File type Python version Upload date Hashes
Filename, size read_only_attributes-1.2-py3-none-any.whl (4.3 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size read-only-attributes-1.2.tar.gz (15.2 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page