2014-12-30 01:05:20 +01:00
|
|
|
# Copyright (C) 2013-2014 Eygene A. Ryabinkin and contributors
|
2013-02-05 04:49:56 +01:00
|
|
|
#
|
|
|
|
# Collection of classes that implement const-like behaviour
|
|
|
|
# for various objects.
|
|
|
|
|
|
|
|
import copy
|
|
|
|
|
2020-08-29 20:00:02 +02:00
|
|
|
|
2020-08-29 21:44:18 +02:00
|
|
|
class ConstProxy():
|
2014-12-30 01:05:20 +01:00
|
|
|
"""Implements read-only access to a given object
|
|
|
|
that can be attached to each instance only once."""
|
2013-02-05 04:49:56 +01:00
|
|
|
|
2014-12-30 01:05:20 +01:00
|
|
|
def __init__(self):
|
|
|
|
self.__dict__['__source'] = None
|
2013-02-05 04:49:56 +01:00
|
|
|
|
2014-12-30 01:05:20 +01:00
|
|
|
def __getattr__(self, name):
|
|
|
|
src = self.__dict__['__source']
|
2020-08-30 11:18:18 +02:00
|
|
|
if src is None:
|
2014-12-30 01:05:20 +01:00
|
|
|
raise ValueError("using non-initialized ConstProxy() object")
|
|
|
|
return copy.deepcopy(getattr(src, name))
|
2013-02-05 04:49:56 +01:00
|
|
|
|
2014-12-30 01:05:20 +01:00
|
|
|
def __setattr__(self, name, value):
|
2020-08-29 20:00:02 +02:00
|
|
|
raise AttributeError("tried to set '%s' to '%s' for constant object" % \
|
|
|
|
(name, value))
|
2013-02-05 04:49:56 +01:00
|
|
|
|
2014-12-30 01:05:20 +01:00
|
|
|
def __delattr__(self, name):
|
2020-08-29 20:00:02 +02:00
|
|
|
raise RuntimeError("tried to delete field '%s' from constant object" % \
|
|
|
|
(name))
|
2013-02-05 04:49:56 +01:00
|
|
|
|
2014-12-30 01:05:20 +01:00
|
|
|
def set_source(self, source):
|
|
|
|
""" Sets source object for this instance. """
|
2020-08-30 11:18:18 +02:00
|
|
|
if (self.__dict__['__source'] is not None):
|
2014-12-30 01:05:20 +01:00
|
|
|
raise ValueError("source object is already set")
|
|
|
|
self.__dict__['__source'] = source
|