{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/access-classmethod-like-property/",
  "description": "Learn how to access Python classmethods like property methods using metaclasses or Python 3.9+ decorator stacking for Enum classes.",
  "path": "/python/access-classmethod-like-property/",
  "publishedAt": "2021-11-26T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python"
  ],
  "textContent": "I wanted to add a helper method to an Enum class. However, I didn't want to make it a\nclassmethod as property method made more sense in this particular case. Problem is, you\naren't supposed to initialize an enum class, and property methods can only be accessed\nfrom the instances of a class; not from the class itself.\n\nWhile sifting through Django 3.2's codebase, I found this neat trick to make a classmethod\nthat acts like a property method and can be accessed directly from the class without\ninitializing it.\n\nIf you run the script, you'll see the following output:\n\nWhile the previous example is quite impressive, I still don't like the solution as it\nrequires creating a metaclass and doing a bunch of magic to achieve something so simple.\nLuckily, Python3.9+ makes it possible without any additional magic. Notice the example\nbelow:\n\nThe only thing that matters here is the order of the property and classmethod decorator.\nPython applies them from bottom to top. Changing the order will make it behave unexpectedly.\n\nComplete example with tests\n\nRunning this will print out the following:",
  "title": "Access 'classmethod's like 'property' methods in Python"
}