is there any way to prevent side effects in python?

后端 未结 7 2017
别跟我提以往
别跟我提以往 2021-02-05 15:14

Is there any way to prevent side effects in python? For example, the following function has a side effect, is there any keyword or any other way to have the python complain abou

7条回答
  •  野的像风
    2021-02-05 15:53

    About the only way to enforce that would be to overwrite the function specification to deepcopy any arguments before they are passed to the original function. You could to that with a function decorator.

    That way, the function has no way to actually change the originally passed arguments. This however has the "sideeffect" of a considerable slowdown as the deepcopy operation is rather costly in terms of memory (and garbage-collection) usage as well as CPU consumption.

    I'd rather recommend you properly test your code to ensure that no accidental changes happen or use a language that uses full copy-by-value semantics (or has only immutable variables).

    As another workaround, you could make your passed objects basically immutable by adding this to your classes:

     """An immutable class with a single attribute 'value'."""
     def __setattr__(self, *args):
         raise TypeError("can't modify immutable instance")
     __delattr__ = __setattr__
     def __init__(self, value):
         # we can no longer use self.value = value to store the instance data
         # so we must explicitly call the superclass
         super(Immutable, self).__setattr__('value', value)
    

    (Code copied from the Wikipedia article about Immutable object)

提交回复
热议问题