Python I/O (1) - Stream

steadycode·2022년 11월 22일
0

Python 이라는 언어를 다루면서 파일을 다뤄봤을 것이다. 파일이 텍스트 파일이라고 가정했을 때의 data format은 csv, json, dataframe 등이 있을 것이고, data type은 string (text), byte (binary) 등이 있을 것이다. 만약 파일이 이미지라고 하면, data format은 jpeg, PNG 등이 있을 것이며, 이를 구성하는 data type은 byte일 것이다.

그렇다면 이러한 파일을 읽어왔을 때, python 내부에서는 이러한 데이터들이 어떻게 표현될까? python에서는 파일을 읽어올 때 이를 io 라는 class로 표현을 한다. 본 글에서는 이러한 python 의 class io (혹은 I/O)를 활용하기 위해 stream 이라는 객체의 정의에 대해 다룬다.


Stream in Python I/O

python 공식문서에서는 io 객체를 다음과 같이 표현한다.

Core tools for working with streams

그렇다면 여기서 말하는 stream 의 정의란 도대체 무엇일까??

stream

stream 이라는 용어는 python 말고도 다른 언어에서도 흔히 사용하는 용어이다. 각 언어에서 stream 은 다음과 같이 정의되었다.

stream in C

C 공식 문서에서는 file 과 stream 의 확실한 구분을 요구하는 것 같다.

a stream is a fairly abstract, high-level concept representing a communications channel to a file, device, or process.

For historical reasons, the type of the C data structure that represents a stream is called FILE rather than “stream”. Since most of the library functions deal with objects of type FILE *, sometimes the term file pointer is also used to mean “stream”. This leads to unfortunate confusion over terminology in many books on C. This manual, however, is careful to use the terms “file” and “stream” only in the technical sense.

C 에서는 stream 을 표현하기 위한 용도로 FILE 이라는 데이터 타입을 사용한다. 많은 글들이 FILE 을 파일이라고 부르고, FILE* 를 stream pointer 가 아닌 file pointer, 혹은 stream 이라고 부르고 있다고 하는데, 이는 잘못된 표현으로 생각된다. 더 자세히 풀어쓸 수 있지만 본 글에서는 C에서는 stream 을 FILE이라는 데이터 타입을 사용하여 표현하고, 연결된 file, device 혹은 process 와 관련된 meta-data information, connection information 등의 정보를 가지고 있다고만 파악하고 넘어간다.

  • Data Type of stream object in C : FILE

stream in JavaScript (NodeJS)

JavaScript 역시 다음과 같이 stream을 정의한다.

A stream is an abstract interface for working with streaming data in Node.js. The node:stream module provides an API for implementing the stream interface.

추가적으로 다음과 같은 특성을 예시로 제시했다.

  • Writable: streams to which data can be written (for example, fs.createWriteStream()).
  • Readable: streams from which data can be read (for example, fs.createReadStream()).
  • Duplex: streams that are both Readable and Writable (for example, net.Socket).
  • Transform: Duplex streams that can modify or transform the data as it is written and read (for example, zlib.createDeflate()).

stream in Python

Python 공식 문서에서는 file 과 stream 을 동의어로 취급하는 것 같다.

A concrete object belonging to any of these categories is called a file object. Other common terms are stream and file-like object.

아마 python 자체가 확실한 정의를 토대로 발전한 것이 아닌, 많은 유저들이 활용하면서 발전했기에 복잡한 용어들의 정의를 확실하게 하지 않고 간단하게 표현한 것 같다.

conclusion

정리를 하자면, stream 이란 file 말고도 양측에 메모리 공간을 두고, 위 메모리 공간을 통해 '소통'하는 채널을 정의하는 것 같다. 따라서 file 말고도, process-to-process, network socket 등의 읽고 쓰기가 가능한 모든 객체에 활용되는 개념이라고 생각하면 될 것 같다.

profile
steadycode

0개의 댓글