I need to create an object that will raise a custom exception, UnusableObjectError , when it will be used in any way (creating it should not throw an exception).
a = UnusableClass()
I came up with the code below, which seems to behave as expected.
class UnusableObjectError(Exception): pass CLASSES_WITH_MAGIC_METHODS = (str(), object, float(), dict()) # Combines all magic methods I can think of. MAGIC_METHODS_TO_CHANGE = set() for i in CLASSES_WITH_MAGIC_METHODS: MAGIC_METHODS_TO_CHANGE |= set(dir(i)) MAGIC_METHODS_TO_CHANGE.add('__call__') # __init__ and __new__ must not raise an UnusableObjectError # otherwise it would raise error even on creation of objects. MAGIC_METHODS_TO_CHANGE -= {'__class__', '__init__', '__new__'} def error_func(*args, **kwargs): """(nearly) all magic methods will be set to this function.""" raise UnusableObjectError class UnusableClass(object): pass for i in MAGIC_METHODS_TO_CHANGE: setattr(UnusableClass, i, error_func)
(some improvements made as suggested by Duncan in the comments)
Questions:
Is there an already existing class that behaves as described?
If not, is there a flaw in my UnusableClass() (for example, a situation where using class instances did not raise an error), and if so, how can I fix these flaws?
source share