Skip to content

Instantly share code, notes, and snippets.

@James-Ansley
Last active October 5, 2024 01:38
Show Gist options
  • Save James-Ansley/84e8a6de6610b06101736716490a3e2d to your computer and use it in GitHub Desktop.
Save James-Ansley/84e8a6de6610b06101736716490a3e2d to your computer and use it in GitHub Desktop.
A simple decorator for write-only attributes

It's the Python feature we've all been waiting for — write-only attributes. This simple decorator makes it so all your attributes are write-only:

@kablooey
class Foo:
    def __init__(self, x):
        self.x = x

Set these attributes to your heart's content:

foo = Foo(1)
foo.x = 2
foo.x = 3

Knowing that they are safely write-only — keeping them locked aray from prying eyes:

print(foo.x)

The above code would cause the following exception:

Traceback (most recent call last):
  File "...", line ..., in <module>
    print(foo.x)
          ^^^^^
  File "...", line ..., in __get__
    raise Exception("Bang!")
Exception: Bang!

def kablooey(cls):
instances = {}
class Bang:
def __init__(self, name):
self.name = name
def __get__(self, instance, owner):
raise Exception("Bang!")
def __set__(self, instance, value):
instances[(id(instance), self.name)] = value
og_setattr = cls.__setattr__
def _setattr(instance, name, value):
if not isinstance(cls.__dict__.get(name, None), Bang):
type.__setattr__(cls, name, Bang(name))
og_setattr(instance, name, value)
cls.__setattr__ = _setattr
return cls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment