프로그래밍 문법/python

파이썬 함수주석(Function Annotations), (->, : , __anotations__)

씩씩한 IT블로그 2022. 1. 3. 09:22
반응형

파이썬 Function Annotations

파이썬에서 함수를 구현할때, input과 output의 type을 주석으로서 명시해줄 수 있다.

다음과 같이 ":" 과 "->"를 하고 타입을 명시해준다.

def f(a:str, b:int, c:bool)->list:

이는 a는 string타입, b는 int타입, c는 bool타입, 그리고 함수 리턴값은 list타입을 의미한다.

 

예시

1. code

def f(a:str, b:int, c:bool)->list:
    print("a의 데이터타입은 string : ",a)
    print("b의 데이터타입은 int : ",b)
    print("c의 데이터타입은 bool : ",c)
    return [a,b,c]

return_value = f("hello",10,True)
print("return 데이터타입은 list : ",return_value)

 

2. return

a의 데이터타입은 string :  hello
b의 데이터타입은 int :  10
c의 데이터타입은 bool :  True
return 데이터타입은 list :  ['hello', 10, True]

 

확인

아래와 같은 방법으로 값을 확인할 수 있다

print(f.__annotations__)
{'a': <class 'str'>, 'b': <class 'int'>, 'c': <class 'bool'>, 'return': <class 'list'>}

 

주의

주석과 다른 타입의 데이터가 들어간다고 에러가 나진 않는다!

c++처럼 변수를 선언해주는것이 아니라 단순히 주석을 달아주는 것이므로 달아준 주석과 다른 타입의 데이터가 들어간다고 에러가 나는것은 아니다.

diff = f(1,"hi",1.6)
print(diff)
의 데이터타입은 string :  1
b의 데이터타입은 int :  hi
c의 데이터타입은 bool :  1.6
[1, 'hi', 1.6]

 

원문 레퍼런스

https://www.python.org/dev/peps/pep-3107/

반응형