Open santokalayil opened 2 months ago
How to use getstate and setstate for pickling in Python:
Purpose:
__getstate__
: Prepares an object for pickling by returning a dictionary containing the object's state.
__setstate__
: Restores an object's state from the pickled data.
Usage:
Define __getstate__
:
Implement the __getstate__
method within your class.
Return a dictionary containing the attributes you want to pickle.
Include only the attributes that are necessary for reconstructing the object.
Exclude attributes that are not pickleable or that should not be persisted.
Define __setstate__
:
Implement the __setstate__
method within your class.
Take a dictionary as an argument.
Set the attributes of the object using the values in the dictionary.
Ensure that the dictionary keys correspond to the attributes you defined in __getstate__
.
Example:
import pickle
class MyClass:
def __init__(self, a, b):
self.a = a
self.b = b
def __getstate__(self):
return {'a': self.a, 'b': self.b}
def __setstate__(self, state):
self.a = state['a']
self.b = state['b']
# Create an instance of MyClass
obj = MyClass(10, 20)
# Pickle the object
with open('my_object.pkl', 'wb') as f:
pickle.dump(obj, f)
# Unpickle the object
with open('my_object.pkl', 'rb') as f:
unpickled_obj = pickle.load(f)
print(unpickled_obj.a) # Output: 10
print(unpickled_obj.b) # Output: 20
class P:
def __init__(self, path: str) -> None:
self.path = path
def __add__(self, other: str) -> "P":
return P(self.path + "/" + other)
def __radd__(self, other: str) -> "P":
return P(other + "/" + self.path)
def __repr__(self) -> str:
return f"P({self.path})"
p = P("santo")
p + "sajan"
Similar to this, we can all r___
dunder methos like __rtruediv__
etc.
Here's a comprehensive list of dunder methods that can be overloaded in Python:
Arithmetic Operators:
add: Addition (+) sub: Subtraction (-) mul: Multiplication (*) truediv: True division (/) floordiv: Floor division (//) mod: Modulus (%) pow: Exponentiation (**) neg: Negation (-) pos: Positive (+) abs: Absolute value (abs()) invert: Bitwise inversion (~) lshift: Left shift (<<) rshift: Right shift (>>) and: Bitwise and (&) or: Bitwise or (|) xor: Bitwise xor (^)
Comparison Operators:
eq: Equality (==) ne: Inequality (!=) lt: Less than (<) le: Less than or equal to (<=) gt: Greater than (>) ge: Greater than or equal to (>=)
Container Operators:
len: Length (len()) getitem: Item access ([]) setitem: Item assignment ([]) delitem: Item deletion (del []) contains: Membership test (in) iter: Iterator (iter()) next: Next item (next())
Attribute Access:
getattr: Attribute access (object.attribute) setattr: Attribute assignment (object.attribute = value) delattr: Attribute deletion (del object.attribute)
Callable Objects:
call: Callable object (object()) String Representation:
str: String representation (str(object)) repr: Official string representation (repr(object)) Context Managers:
enter: Enter context (with object:) exit: Exit context (with object:) Pickling:
getstate: Prepare for pickling setstate: Restore from pickled state
Other:
hash: Hash value (hash(object)) format: Format string (format(object)) sizeof: Size in bytes (sys.getsizeof(object)) reduce: Pickle representation __reduce_ex__: Pickle representation with protocol version
By overloading these methods, you can customize the behavior of your custom objects and make them more Pythonic and intuitive to use.