-
Notifications
You must be signed in to change notification settings - Fork 5
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
타입으로 견고하게 다형성으로 유연하게 2주차 - 김우현 #455
base: main
Are you sure you want to change the base?
Conversation
우측에 있는 |
우측에 있는 |
@TaeHyoungKwon auto reviewer가 안되는데 제가 혹시 설정중 놓친게 있을까요?ㅜ |
#441 에서 확인했습니다ㅜ |
우현님 기존 기능을 대체할 gh api를 활용한 create_pr.sh 을 만들게 되면서, 기존에 있었던 github actions 는 제거하려고 합니다! |
|
||
**Q. 논의내용** | ||
|
||
Quiz. Java에는 bottom type이 있을까요? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
검색해서는 해당 내용을 찾을 수 없어서, 지피티 문의결과는 없다라고 말해주네요 지피티 답변 상으론, 애초에 자바 언어 설계 철학에 매칭되지 않는 부분으로 보이네요
greet(employee) # Works because Employee is a subtype of Person | ||
``` | ||
|
||
2. "집합론적 타입"은 무슨 의미일까요? 이해는 하지 못했지만, 그냥 넘어가도 핵심을 이해하는데는 문제가 없어서 지나쳤습니다. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저도 대략적으로만 이해했는데, 책에 나온대로, 책에서 설명하고자 하는 키워드들(최대, 최소, 이거나, 이면서 등등)이 집합론과 관련 있는 것이다보니 쓴 제목 같은데, 책 전체 맥락을 이해하는데 중요한 정보는 아니였던거 같습니다
|
||
Quiz. Java에는 bottom type이 있을까요? | ||
|
||
1. Class뿐만 아니라 Record(e.g. struct)에도 subtyping 이 있습니다. width subtyping, depth subtyping이 있습니다. 이를 활용한 경험이 있으시면 공유해주세요. 아쉽게도 제가 주로 사용하는 언어에서는 활용해볼 수 없었네요. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
width subtyping이 필요한 속성(또는 메서드)이 존재하면, 추가적인 속성이 있어도 허용된다는 개념이고,
Depth Subtyping (깊이 서브타이핑) 가 객체의 구성 요소(속성 혹은 메서드)의 타입이 보다 구체적인 서브타입인 경우에도 전체 타입 관계가 성립하는 것 이라고 가정 했을 때,
python2를 기준으로, duck typing의 관점에서 위 두가지는 모두 많이 사용 했던 것 같습니다
다만, python3.8 부터는 Protocol 이란 것이 생겨서, 런타임 전에 mypy라는 타입체커로 타입이 올바른지 검사할 수 있도록 duck typing의 유연성과 정적 검사의 안전성을 동시에 누릴 수 있게 되었습니다
but, 제 개인적으로 python3으로 넘어오고나선, duck typing이나 Protocol 보단, python3.X 초반 에 생긴 추상 클래스, 추상메소드를 훨씬 많이 활용 합니다
#### **Example in Python**: | ||
```python | ||
class Person: | ||
def __init__(self, name: str, age: int): | ||
self.name = name | ||
self.age = age | ||
|
||
class Employee(Person): | ||
def __init__(self, name: str, age: int, department: str): | ||
super().__init__(name, age) | ||
self.department = department | ||
|
||
def greet(person: Person): | ||
print(f"Hello, {person.name}, age {person.age}") | ||
|
||
employee = Employee("Alice", 30, "HR") | ||
greet(employee) # Works because Employee is a subtype of Person | ||
``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[참고]
파이썬 3.8 이후 나온 typing.Protocol을 활용하여서, Employee와 Person 간 상속 관계를 끊고, 구조에 의한 서브타입으로 아래와 같이 리팩토링 할 수 있고, mypy를 통해서 타입체크를 할 수 있습니다
from typing import Protocol
# Person과 Employee의 상속 관계를 끊고, 대신에 구조에 의한 서브타입을 위해서 프로토콜을 정의
class PersonProtocol(Protocol):
name: str
age: int
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
class Employee:
def __init__(self, name: str, age: int, department: str):
self.name = name
self.age = age
self.department = department
# Employee가 PersonProtocol을 따르는지 확인
def greet(person: PersonProtocol):
print(f"Hello, {person.name}, age {person.age}")
employee = Employee("Alice", 30, "HR")
greet(employee)
# 실행 시 문제 없음
╰─➤ python sample.py
Hello, Alice, age 30
# mypy 실행 시 문제 없음
Success: no issues found in 2 source files
from typing import Protocol
class PersonProtocol(Protocol):
name: str
age: int
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
class Employee:
def __init__(self, name: str, height: int, department: str):
self.name = name
self.height = height # PersonProtocol에 없는 속성으로 변경
self.department = department
def greet(person: PersonProtocol):
print(f"Hello, {person.name}, height {person.height}")
employee = Employee("Alice", 170, "HR")
greet(employee) # mypy 실행 시, 구조에 의한 서브타입이 충족되지 않기 떄문에, 에러 발생
# 실행 시, 문제 없음
╰─➤ python sample.py
Hello, Alice, height 170
# but, mypy 실행 시는 에러 발생
# 이를 통해서, 타입에 의한 문제를 미리 발견 가능
╰─➤ mypy .
sample.py:23: error: "PersonProtocol" has no attribute "height" [attr-defined]
sample.py:27: error: Argument 1 to "greet" has incompatible type "Employee"; expected "PersonProtocol" [arg-type]
sample.py:27: note: "Employee" is missing following "PersonProtocol" protocol member:
sample.py:27: note: age
Found 2 errors in 1 file (checked 2 source files)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이번에도 좋은 논의 내용 감사합니다.
특히 **bottom type**은 가장 흥미로운 컨셉이었습니다. 몇몇 용어는 번역 방향을 달리하면 더 나을 것 같다는 생각도 들었습니다. 예를 들어: | ||
- `top type` → `최대타입` 대신 `최상위타입`으로, | ||
- `bottom type` → `최소타입` 대신 `최하위타입`으로 번역하는 것이 더 적합해 보였습니다. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저자가 한국 사람이다 보니 한국어로 표현하면 좋을 자기 만의 표현을 한 것이라고 봅니다.
이거나 타입, 이면서 타입 같은 표현도 그렇다고 생각하는데
언뜻 보면 합집합, 교집합이 더 쉽다고 느낄 수도 있을 법 한데 합집합, 교집합은 또 한자어이고 분명 일본어 교재에서 번역됐을 단어라
저자의 표현력에 대한 고민의 흔적이 조금 보였다 라고 이해했습니다.
|
||
**Q. 논의내용** | ||
|
||
Quiz. Java에는 bottom type이 있을까요? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
책의 예시가 TypeScript와 Scala 뿐이었고
저도 bottom type에 익숙하지 않은 터라
책에 나온 예제를 실행시켜 보면서 확인해 봤습니다.
제가 이해했을 때는 최대 타입으로 해도 되지 않을까? 였는데
책의 길고 자세한 설명 상, 어차피 계산되지 않을 꺼고 열어보지 않을 타입이라면? 에 대한 이해를 계속 하려고 하다 보니
never, Nothing이라는 단어 자체를 받아들이는 쪽으로 가게 되더라고요.
우현님의 논의 주제는 간단한 질문이지만
생각할게 많다고 보고 싶습니다.
greet(employee) # Works because Employee is a subtype of Person | ||
``` | ||
|
||
2. "집합론적 타입"은 무슨 의미일까요? 이해는 하지 못했지만, 그냥 넘어가도 핵심을 이해하는데는 문제가 없어서 지나쳤습니다. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저도 태형님 의견처럼 처음에 수학적인 용어로 설명하기 위해서 나열한 것이고 이후 책 내용 이해하는 데는 중요한 단어는 아니었습니다.
|
||
Quiz. Java에는 bottom type이 있을까요? | ||
|
||
1. Class뿐만 아니라 Record(e.g. struct)에도 subtyping 이 있습니다. width subtyping, depth subtyping이 있습니다. 이를 활용한 경험이 있으시면 공유해주세요. 아쉽게도 제가 주로 사용하는 언어에서는 활용해볼 수 없었네요. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
제가 쓰는 언어도 with and depth subtype에 대한 개념은 없어서 경험은 없지만
wikipedia에 개념적인 설명이 있어서 조금 살펴보게 됐습니다.
책에 설명하는 용어를 따라 Java나 C# 같이 이름에 의한 서브타이핑 언어는 지원이 불가능한데
처음부터 타입 검사에 엄격하기에 width subtyping이 불가능 합니다.
이름에 의한 서브타이핑이므로 depth subtyping도 불가능합니다.
태형님이 지원 여부에 대한 테이블을 적어 줘서 많은 도움이 됐고
주로 함수형 언어 혹은 동적 언어에서 subtyping의 제약이 많이 없는 것으로 보이네요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Java에는 bottom type이 있을까요?
저도 궁금해서 찾아보았지만 자바에는 없는 개념인것 같습니다!
그나마 유사한 개념으로 null, Exception이 있는것 같아요.
greet(employee) # Works because Employee is a subtype of Person | ||
``` | ||
|
||
2. "집합론적 타입"은 무슨 의미일까요? 이해는 하지 못했지만, 그냥 넘어가도 핵심을 이해하는데는 문제가 없어서 지나쳤습니다. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
최대 타입, 최소 타입, 이거나 타입, 이면서 타입이 각각 수학 집합론의 전체 집합, 공집합, 합집합, 교집합으로 이해를 한다면 좀 더 쉬워서 집합론적 타입이라는 표현을 사용한 것 같다는 생각입니다. 여기서 공집합인 최소 타입의 경우에 이해하기가 조금 어려웠습니다.
이를 이해하기 위해 추가적으로 최대 타입과 최소 타입의 상속관계를 나타내보면 아래와 같이 되려나? 라고 생각해보게 되었습니다. 이렇게 되면 최소 타입은 모든 타입의 서브타입인데 모든 타입의 내용을 실질적으로 갖고 있을 수는 없으므로 공집합의 개념처럼 없는 데 빈 상자만 표현하는 요소로 사용되는 것인가? 라는 생각이 들었습니다.
아주 재미있게 읽었습니다. 챕터3도 기대가 되네요.