First rule: do not change containers: create new ones.
Therefore, do not change your incoming dictionary, create a new dictionary with a subset of keys.
self.fields = dict( key, value for key, value in fields.items() if accept_key(key, data) )
Such methods, as a rule, are slightly more effective than passing and removing bad elements. More generally, it is often easier to avoid modifying objects and creating new ones instead.
The second general rule: do not change containers after they are turned off.
Normally, you cannot assume that the containers to which you transferred the data made their own copies. As a result, do not try to modify the containers that you specified. Any changes must be made before data transfer. As soon as you transfer the container to someone else, you are no longer its sole owner.
The third general rule: do not modify containers that you have not created.
If you received a container, you do not know who else can use the container. Therefore, do not change it. Either use the unmodified version or call rule1 by creating a new container with the desired changes.
Fourth General Rule: (stolen from Ethan Furman)
Some functions must change the list. This is their job. If so, make it visible in the function name (for example, add and continue list methods).
Putting it all together:
A piece of code should only modify a container if it is the only piece of code with access to that container.
Winston ewert
source share