Skip to content

Instantly share code, notes, and snippets.

@nazavode
Last active December 17, 2015 08:35
Show Gist options
  • Save nazavode/53f09cc550e1991605c8 to your computer and use it in GitHub Desktop.
Save nazavode/53f09cc550e1991605c8 to your computer and use it in GitHub Desktop.
Type-level property decorator.
# -*- coding: utf-8 -*-
#
# Copyright 2015 Federico Ficarelli
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A simple, getter-only class property implementation.
It can be used as a decorator:
>>> class MyMeta(type):
... @classproperty
... def is_badass(cls):
... return True
>>> MyMeta.is_badass
True
It can be used directly as a class as well:
>>> MyClass = type(
... "myclass",
... (),
... { 'is_badass': classproperty(lambda cls: True) }
... )
>>> MyClass.is_badass
True
Obviously, it can be accessed via instances as well:
>>> my_inst = MyClass()
>>> my_inst.is_badass
True
"""
__all__ = (
"classproperty",
)
class classproperty(property): # pylint: disable=invalid-name, too-few-public-methods
""" Class property, to be used as a static, getter-only property. """
def __init__(self, fget, *args, **kwargs):
super().__init__(fget, *args, **kwargs)
self.__doc__ = fget.__doc__
def __get__(self, instance, owner_type):
return self.fget(owner_type)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment