Skip to main content

Python_classproperty

·111 words·1 min·
Python Decorators Property Classmethod Classproperty

I have occasionally desired the ergonomics of a classmethod/property. This works in Python ~3.9+, but is marked as deprecated and scheduled for removal in 3.13.

class OPTIONS:
    lol = 'lol'

    @classmethod
    @property
    def lmao(self):
        return self.lol + ', lmao'

Apparently this only works accidentally, and there are Good and Proper Reasons™️ for removing the ability to combine these two decorators, but if want to use a classproperty, damnit, I want a classproperty!

Enter classproperty:

class classproperty:
    def __init__(self, func):
        self.fget = func

    def __get__(self, instance, owner):
        return self.fget(owner)


class OPTIONS:
    lol = 'lol'

    @classproperty
    def lmao(self):
        return self.lol + ', lmao'


print(OPTIONS.lol)
# >>> lol
print(OPTIONS.lmao)
# >>> lol, lmao

Easy.

Related

Nicegui Social Previews
·246 words·2 mins
Nicegui
NiceGUI Tips: Elegant Dialog Lifecycles
·218 words·2 mins
Nicegui Dialog Boxes Code Organization
Code Generation Case Study: Firmware Configuration
·2708 words·13 mins
Embedded C Python Codegen