Coverage for src/gncpy/utilities.py: 0%
33 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-13 06:15 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-13 06:15 +0000
1import inspect
4# helper classes to allow for classproperties similar to class methods
5# see https://stackoverflow.com/questions/5189699/how-to-make-a-class-property
6# for details
7class ClassPropertyDescriptor(object):
8 def __init__(self, fget, fset=None):
9 self.fget = fget
10 self.fset = fset
12 def __get__(self, obj, klass=None):
13 if klass is None:
14 klass = type(obj)
15 return self.fget.__get__(obj, klass)()
17 def __set__(self, obj, value):
18 if not self.fset:
19 raise AttributeError("can't set attribute")
20 if inspect.isclass(obj):
21 type_ = obj
22 obj = None
23 else:
24 type_ = type(obj)
25 return self.fset.__get__(obj, type_)(value)
27 def setter(self, func):
28 if not isinstance(func, (classmethod, staticmethod)):
29 func = classmethod(func)
30 self.fset = func
31 return self
34def classproperty(func):
35 if not isinstance(func, (classmethod, staticmethod)):
36 func = classmethod(func)
38 return ClassPropertyDescriptor(func)
41class ClassPropertyMetaClass(type):
42 def __setattr__(self, key, value):
43 if key in self.__dict__:
44 obj = self.__dict__.get(key)
45 if obj and type(obj) is ClassPropertyDescriptor:
46 return obj.__set__(self, value)
48 return super(ClassPropertyMetaClass, self).__setattr__(key, value)