[Python] Struct 사용하기
Struct
Struct는 C 구조체를 Python String으로 변환해주는 모듈이다.
C 구조체란 서로 다른 Type을 가진 변수들을 하나로 묶어서 일종의 Class처럼 만든 것이다.
Javascript의 Constructor, Python의 DataClass를 생각하면 쉬울 것 같다.
파이썬 2.7까지는 pack이 string을 return 했지만 3부터는 bytes 타입을 return하는 듯 하다.
import struct
struct.pack('구조체로 만들 때 사용할 타입', *인자) 이런식으로 하면 bytes 타입의 결과가 리턴이 된다.
ex)
struct.pack('hhl', 1, 2, 3) # b'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03'
struct.unpack('hhl', b'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03') # (1, 2, 3)
calcsize('hhl') # 8
# hhl은 short, short, long type을 의미한다.
# 즉 1,2,3을 각각 short, short, long 타입으로 변환한 구조체를 만들어준다.
이것의 활용례는 뭐가 있을지 생각해봤는데,
-
Model 단위로 움직이는 데이터의 serialization
-
서버-클라 통신간에 민감한 정보가 있으면 struct, encrypt 과정을 거쳐 안전성을 올리기.
from collections import namedtuple
Student = namedtuple('Student', 'name serialnum school gradelevel')
Student._make(unpack('<10sHHb', record))
Data 전송간에 발생할 수 있는 여러 이슈들을 이것을 잘 이용하면 용이하게 data send/receive가 가능할 것 같다.
댓글
댓글 쓰기