Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌐 Add Korean translation for docs/ko/docs/python-types.md #2267

Merged
merged 30 commits into from
Jan 22, 2024
Merged
Changes from 5 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
eb3ac10
Add Korean Translation for Python-types #2017
jrim Oct 30, 2020
a7a828c
Update docs/ko/docs/python-types.md
jrim Nov 6, 2020
c60088b
Update docs/ko/docs/python-types.md
jrim Nov 6, 2020
6c28c04
Update docs/ko/docs/python-types.md
jrim Nov 6, 2020
d2a0e65
Update docs/ko/docs/python-types.md
jrim Nov 6, 2020
d4bdc81
Update docs/ko/docs/python-types.md
jrim May 4, 2021
efe4f2c
Update docs/ko/docs/python-types.md
jrim May 4, 2021
79adb0e
Update docs/ko/docs/python-types.md
jrim May 4, 2021
698665e
Update docs/ko/docs/python-types.md
jrim May 4, 2021
e646215
Update docs/ko/docs/python-types.md
jrim May 4, 2021
e596484
Update docs/ko/docs/python-types.md
jrim May 4, 2021
2e4f16d
Update docs/ko/docs/python-types.md
jrim May 4, 2021
c3df2b7
Update docs/ko/docs/python-types.md
jrim May 4, 2021
d5f04dc
Update docs/ko/docs/python-types.md
jrim May 4, 2021
f8f5c46
Update docs/ko/docs/python-types.md
jrim May 4, 2021
a214848
Update docs/ko/docs/python-types.md
jrim May 4, 2021
8947f18
Update docs/ko/docs/python-types.md
jrim May 4, 2021
a1bf22c
Update docs/ko/docs/python-types.md
jrim May 4, 2021
4b3c49f
Update docs/ko/docs/python-types.md
jrim May 4, 2021
a489d17
Update docs/ko/docs/python-types.md
jrim May 4, 2021
b105db1
Update docs/ko/docs/python-types.md
jrim May 4, 2021
0ae56a2
Update docs/ko/docs/python-types.md
jrim May 4, 2021
a3bcf88
Update docs/ko/docs/python-types.md
jrim May 4, 2021
f68664b
Update docs/ko/docs/python-types.md
jrim May 4, 2021
5364b82
Update docs/ko/docs/python-types.md
jrim May 11, 2021
cd37ecc
Update docs/ko/docs/python-types.md
jrim May 11, 2021
fc793b9
Update docs/ko/docs/python-types.md
jrim May 11, 2021
cb4b30b
Update docs/ko/docs/python-types.md
jrim May 11, 2021
6cf7cda
Merge branch 'master' into translation/ko
tiangolo Jun 26, 2023
655e68d
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jun 26, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
314 changes: 314 additions & 0 deletions docs/ko/docs/python-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
# 파이썬 타입 소개

**Python 3.6+**는 "타입 힌트"를 선택적으로 제공합니다.

**"타입 힌트"**는 (Python 3.6+)부터 제공하는 새로운 문법으로 변수의 <abbr title="for example: str, int, float, bool">타입</abbr>을 지정할 수 있습니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

변수의 타입을 지정하면 에디터와 툴이 더 많은 도움을 줄 수 있게 됩니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

이 문서는 파이썬 타입 힌트에 대한 **빠른 튜토리얼 / 내용환기** 수준의 문서입니다. 여기서는 **FastAPI**를 쓰기 위한 최소한의 내용만을 다룹니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

**FastAPI**는 타입 힌트에 기반을 두고 있으며, 이는 많은 장점과 이익이 있습니다.

비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다.

!!! note
jrim marked this conversation as resolved.
Show resolved Hide resolved
파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요.

## 동기 부여

간단한 예제부터 시작해봅시다:

```Python
{!../../../docs_src/python_types/tutorial001.py!}
```

이 프로그램을 실행한 결과값:

```
John Doe
```

함수는 아래와 같이 실행됩니다:

* `first_name`과 `last_name`를 받습니다.
* `title()`로 각 첫 문자를 대문자로 변환시킵니다.
* 두 단어를 중간에 공백을 두고 <abbr title="두 개를 하나로 차례차례 이어지게 하다">연결</abbr>합니다.

```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial001.py!}
```

### 코드 수정

이건 매우 간단한 프로그램입니다.

그런데 처음부터 작성한다고 생각을 해봅시다.

여러분은 매개변수를 준비했고, 함수를 정의하기 시작했을 겁니다.

이때 "첫 글자를 대문자로 바꾸는 함수"를 호출해야 합니다.

`upper`였나? 아니면 `uppercase`? `first_uppercase`? `capitalize`?

그때 개발자들의 오랜 친구, 에디터 자동완성을 시도해봅니다.

당신은 `first_name`를 입력한 뒤 점(`.`)을 입력하고 자동완성을 켜기 위해서 `Ctrl+Space`를 눌렀습니다.

하지만 슬프게도.. 아무런 도움이 되지 않네요:
jrim marked this conversation as resolved.
Show resolved Hide resolved

<img src="/img/python-types/image01.png">

### 타입을 추가하자
jrim marked this conversation as resolved.
Show resolved Hide resolved

이전 버전에서 한 줄만 수정해봅시다.

저희는 이 함수의 파라미터 부분:
jrim marked this conversation as resolved.
Show resolved Hide resolved

```Python
first_name, last_name
```

을 아래와 같이 바꿀 겁니다:

```Python
first_name: str, last_name: str
```

이게 다에요.

이게 "타입 힌트"입니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial002.py!}
```

타입힌트는 기본 값을 선언하는 것과는 다릅니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

```Python
first_name="john", last_name="doe"
```

여러 차이가 있습니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

(`=`) 대신 (`:`)을 쓰고,
jrim marked this conversation as resolved.
Show resolved Hide resolved

일반적으로 타입힌트를 추가한다고 해서 특별하게 어떤 일이 일어나지도 않습니다.

하지만, 타입 힌트를 사용해서 다시 중간의 코드를 작성한다고 생각해보세요.
jrim marked this conversation as resolved.
Show resolved Hide resolved

같은 상황에서 `Ctrl+Space`로 자동완성을 작동시키면,

<img src="/img/python-types/image02.png">

아래와 같이 "그렇지!"하는 옵션이 나올때까지 스크롤을 내려서 볼 수 있습니다:

<img src="/img/python-types/image03.png">

## 더 큰 동기부여

아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다:

```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial003.py!}
```

에디터는 변수의 타입을 알기 때문에, 자동완성 뿐 아니라 에러 내용도 확인할 수 있습니다:
jrim marked this conversation as resolved.
Show resolved Hide resolved

<img src="/img/python-types/image04.png">

이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다:

```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial004.py!}
```

## 타입 선언

방금 함수의 매개변수로써 타입 힌트를 주로 사용하는 방법을 알아보았습니다.

이 방법을 **FastAPI**에서도 주로 사용하게 됩니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

### Simple 타입
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace "Simple" with Korean. I think you can use "심플" or "단순", but not "순수".


`str`뿐 아니라 모든 파이썬 표준 타입을 선언할 수 있습니다.

예를 들면:

* `int`
* `float`
* `bool`
* `bytes`

```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial005.py!}
```

### 타입 매개변수를 활용한 Generic(제네릭) 타입
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
### 타입 매개변수를 활용한 Generic(제네릭) 타입
### 타입 매개변수가 있는 제네릭 타입


`dict`, `list`, `set`, `tuple`과 같은 값을 저장할 수 있는 데이터 구조가 있고, 내부의 값은 각자의 타입을 가질 수도 있습니다.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`dict`, `list`, `set`, `tuple`과 같은 값을 저장할 수 있는 데이터 구조가 있고, 내부의 값은 각자의 타입을 가질 수도 있습니다.
`dict`, `list`, `set`, `tuple`과 같은 값을 저장할 수 있는 자료 구조가 있습니다. 그리고 내부의 값은 각자의 타입을 가질 수도 있습니다.


타입과 내부 타입을 선언하기 위해서는 파이썬 표준 모듈인 `typing`을 이용해야 합니다.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
타입과 내부 타입을 선언하기 위해서는 파이썬 표준 모듈인 `typing`이용해야 합니다.
이러한 타입과 내부 타입을 선언하기 위해서는 파이썬 표준 모듈인 `typing`이용할 수 있습니다.


구체적으로는 아래 타입 힌트를 지원합니다.

#### `List`

예를 들면, `str`의 `list`인 변수를 정의해봅시다.

`typing`에서 `List`(대문자 `L`)를 import 합니다.

```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial006.py!}
```

콜론(`:`) 문법을 이용하여 변수를 선언합니다.

타입으로는 `List`를 넣어줍니다.

이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다.
리스트는 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다.


```Python hl_lines="4"
{!../../../docs_src/python_types/tutorial006.py!}
```

!!! tip
jrim marked this conversation as resolved.
Show resolved Hide resolved
대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다.

이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.

이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
이는 "`items``list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다.
이는 "`items``list`인데, 리스트에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다.


이렇게 함으로써, 에디터는 배열에 들어있는 아이템을 처리할때도 도움을 줄 수 있게 됩니다:
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
이렇게 함으로써, 에디터는 배열에 들어있는 아이템을 처리할때도 도움을 줄 수 있게 됩니다:
이렇게 함으로써, 에디터는 리스트에 들어있는 아이템을 처리할때도 도움을 줄 수 있게 됩니다:


<img src="/img/python-types/image05.png">

타입이 없으면 이건 거의 불가능이나 다름 없습니다.

변수 `item`은 `items`의 개별 요소라는 사실을 알아두세요.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
변수 `item``items`의 개별 요소라는 사실을 알아두세요.
변수 `item`리스트 `items`의 개별 요소라는 사실을 알아두세요.


그리고 에디터는 계속 `str`라는 사실을 알고 도와줍니다.

#### `Tuple`과 `Set`

`tuple`과 `set`도 동일하게 선언할 수 있습니다.

```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial007.py!}
```

이 뜻은 아래와 같습니다:

* 변수 `items_t`는, 차례대로 `int`, `int`, `str`인 `tuple`이다.
* 변수 `items_s`는, 각 아이템이 `bytes`인 `set`이다.

#### `Dict`

`dict`를 선언하려면 컴마로 구분된 2개의 파라미터가 필요합니다.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`dict`를 선언하려면 컴마로 구분된 2개의 파라미터가 필요합니다.
`dict`를 선언하려면 쉼표로 구분된 타입 매개변수 2개가 필요합니다.


첫 번째 매개변수는 `dict`의 키(key)이고,

두 번째 매개변수는 `dict`의 값(value)입니다.
Comment on lines +209 to +211
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
첫 번째 매개변수는 `dict`키(key)이고,
두 번째 매개변수는 `dict`값(value)입니다.
첫 번째 타입 매개변수는 `dict`키입니다.
두 번째 타입 매개변수는 `dict`값입니다:


```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial008.py!}
```

이 뜻은 아래와 같습니다:

* 변수 `prices`는 `dict`이다:
* `dict`의 키(key)는 `str`타입이다. (각 아이템의 이름(name))
* `dict`의 값(value)는 `float`타입이다. (각 아이템의 가격(price))
Comment on lines +220 to +221
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* `dict`의 키(key)는 `str`타입이다. (각 아이템의 이름(name))
* `dict`의 값(value)는 `float`타입이다. (각 아이템의 가격(price))
* `dict`의 키는 `str` 타입이다. (각 항목의 이름)
* `dict`의 값은 `float` 타입이다. (각 항목의 가격)


#### `Optional`

`str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다:

```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial009.py!}
```

`Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다.

#### Generic(제네릭) 타입
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#### Generic(제네릭) 타입
#### 제네릭 타입


이 타입은 대괄호 안에 매개변수를 가지며, 종류는:
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
이 타입은 대괄호 안에 매개변수를 가지며, 종류는:
이 타입은 대괄호 안에 타입 매개변수를 가지며, 종류는:


* `List`
* `Tuple`
* `Set`
* `Dict`
* `Optional`
* ...등등

위와 같은 타입은 **Generic(제네릭) 타입** 혹은 **Generics(제네릭스)**라고 불립니다.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
위와 같은 타입은 **Generic(제네릭) 타입** 혹은 **Generics(제네릭스)**라고 불립니다.
이며 **제네릭 타입(Generic Type)** 혹은 **제네릭스(Generics)**라고 불립니다.


### 타입으로써의 클래스
jrim marked this conversation as resolved.
Show resolved Hide resolved

변수의 타입으로 클래스를 선언할 수도 있습니다.

이름(name)을 가진 `Person` 클래스가 있다고 해봅시다.

```Python hl_lines="1-3"
{!../../../docs_src/python_types/tutorial010.py!}
```

그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다.

```Python hl_lines="6"
{!../../../docs_src/python_types/tutorial010.py!}
```

그리고 역시나 모든 에디터 도움을 받게 되겠죠.
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
그리고 역시나 모든 에디터 도움을 받게 되겠죠.
그리고 역시나 모든 에디터 도움을 받게 됩니다.


<img src="/img/python-types/image06.png">

## Pydantic 모델

<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>은 데이터 검증(Validation)을 위한 파이썬 라이브러리입니다.

당신은 속성들을 포함한 클래스 형태로 "모양(shape)"을 선언할 수 있습니다.

그리고 각 속성은 타입을 가지고 있습니다.

이 클래스를 활용하여서 값을 가지고 있는 인스턴스를 만들게 되면, 필요한 경우에는 적당한 타입으로 변환까지 시키기도 하여 데이터가 포함된 객체를 반환합니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

그리고 결과 객체에 대해서는 에디터의 도움을 받을 수 있게 됩니다.

Pydantic 공식 문서 예시:

```Python
{!../../../docs_src/python_types/tutorial011.py!}
```

!!! info
jrim marked this conversation as resolved.
Show resolved Hide resolved
Pydantic<에 대해 더 배우고 싶다면 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a>
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Pydantic<에 대해 더 배우고 싶다면 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a>
Pydantic에 대해 더 배우고 싶다면 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a>

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about "참고하십시오/확인해보십시오." rather than "참고하세요." ?

Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SueNaEunYang that's better.



**FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다.

[Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}에서 이번 연습보다 더 많은 내용을 볼 수 있습니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

## **FastAPI**에서의 타입 힌트

**FastAPI**는 여러 부분에서 타입 힌트의 장점을 취하고 있습니다.

**FastAPI**에서 타입 힌트를 썼을 때 얻는 장점은:
* **에디터 도움**.
jrim marked this conversation as resolved.
Show resolved Hide resolved
* **타입 확인**.

...그리고 **FastAPI**는 같은 정의를 아래에도 적용합니다:

* **요구사항 정의**: 리퀘스트 경로 파라미터, 쿼리 파라미터, 헤더, 바디, 의존성 등.
* **데이터 변환**: 리퀘스트에서 요구된 타입으로.
* **데이터 검증**: 각 리퀘스트마다:
jrim marked this conversation as resolved.
Show resolved Hide resolved
* 데이터가 유효하지 않은 경우에는 **자동으로 에러**를 발생합니다.
* OpenAPI를 활용한 **API 문서화**:
* 자동으로 상호작용하는 유저 인터페이스에 쓰이게 됩니다.

위 내용이 다소 추상적일 수도 있지만, 걱정마세요. [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}에서 전부 확인 가능합니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved

가장 중요한 건, 파이썬 표준 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠.
jrim marked this conversation as resolved.
Show resolved Hide resolved

!!! info
jrim marked this conversation as resolved.
Show resolved Hide resolved
만약 모든 튜토리얼을 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`에서 제공하는 "cheat sheet"</a>이 좋은 자료가 될 겁니다.
jrim marked this conversation as resolved.
Show resolved Hide resolved