object serialization(직렬화)을 지원하는 pickle 모듈에 대해 알아봅니다.
복잡한 구조의 object들을 넘겨주거나 object의 internal state를 저장해야할 때가 있습니다. 이를 serialization을 통해 수행할 수 있습니다.
파이썬 object structure의 serialization 또는 de-serialization을 지원
import pickle
test_dict = {"dog": "puppy"}
#method 1
with open("test.pickle", "wb") as outfile: #test.pickle 파일에 test_dict 값을 write
pickle.dump(test_dict, outfile)
#method 2
f = open("test.pickle", "wb")
pickle.dump(test_dict, f)
f.close()
import pickle
#method 1
with open("test.pickle", "rb") as infile:
reconstructed_data = pickle.load(infile)
#method 2
f = open("test.pickle", "rb")
reconstructed_data = pickle.load(f)
f.close()
import pickle
class CustomClass:
def __init__(self, data):
print(data)
self.data = data
# Create an object of CustomClass
test_dict = {"dog": "puppy"}
new_class = CustomClass(test_dict)
# Serialize and deserialize
pickled_data = pickle.dumps(new_class)
reconstructed = pickle.loads(pickled_data)
# Verify
print("Data from reconstructed object:", reconstructed.data)
참고문헌
pickle
python object serialization