whoareu@lemmy.ca to Programming@programming.devEnglish · 7 months agowhich python trick or hack you know that you would want to share?message-squaremessage-square45fedilinkarrow-up196arrow-down12
arrow-up194arrow-down1message-squarewhich python trick or hack you know that you would want to share?whoareu@lemmy.ca to Programming@programming.devEnglish · 7 months agomessage-square45fedilink
minus-squaredneaves@lemmy.worldlinkfedilinkEnglisharrow-up6·edit-27 months agoYou can feign immutablility on class attributes by playing with __setattr__. I don’t remember the exact way to do it, but its roughly like this: class YourClass: def __setattr__(self, name, value): if not hasattr(self, name): super().__setattr__(name, value) else: # handle as you wish if the # attr/value already exists. # pass, raise, whatever I say “feign immutability” because there are still cases in which an attr value can change, such as: the underlying attribute contains a list and appending to the list the underlying attribute is a class and modifying the class’s attributes pretty much anything that does “in place” changes, because so much of python is referential and has side effects.
minus-squareQuizzaciousOtter@lemm.eelinkfedilinkarrow-up6·7 months agoI have to mention dataclasses here, especially with frozen=True. Seriously, use dataclasses whenever possible, they’re great.
You can feign immutablility on class attributes by playing with
__setattr__
. I don’t remember the exact way to do it, but its roughly like this:class YourClass: def __setattr__(self, name, value): if not hasattr(self, name): super().__setattr__(name, value) else: # handle as you wish if the # attr/value already exists. # pass, raise, whatever
I say “feign immutability” because there are still cases in which an attr value can change, such as:
I have to mention
dataclasses
here, especially withfrozen=True
.Seriously, use dataclasses whenever possible, they’re great.