찾다
백엔드 개발파이썬 튜토리얼Python에서 함수에 주석 달기

Annotating Functions in Python

최근에 Typescript의 주석 기능에 대한 블로그를 게시했습니다. 방금 약간의 연구를 마쳤고 Python에서 함수에 주석을 추가하는 방법에 대해 더 많이 이해했습니다. 이번 블로그에서는 지난 블로그

와 유사한 예제를 사용하여 Python 함수에 주석을 추가하는 방법을 다룰 예정입니다.

python.analytic.typeCheckingMode를 기본, 표준, 엄격 중 하나로 설정하여 Visual Studio Code에서 유형 주석의 유효성을 검사할 수 있습니다. 기본 및 표준 옵션을 사용한다고 해서 반드시 함수와 변수에 주석을 다는 것은 아니지만 엄격한 옵션은 주석을 다는 것을 보장합니다.

기능 값

이것은 충격을 줄 수 있습니다. 그러나 Python에서는 함수를 반환하고 함수를 값으로 전달할 수 있습니다. 콜백 함수는 실제로 다음과 같이 작성된 Callable 유형을 사용하여 주석이 추가됩니다.

Callable[[argtype1, argtype2, argtype3], returnType]

예를 들어, length(text: str) -> int는 Callable[[str], int]

로 주석이 추가됩니다.

예를 들어

JavaScript의 이 기능

function multiplier(factor){
    return value => factor * value
}

const n = multiplier(6)
n(8) // 48

파이썬에서는 이렇게 작성할 수 있습니다

def multiplier(factor):
    def inner(value):
        return value * factor
    return inner     

n = multiplier(6)
n(8) #48

다음과 같이 문자 그대로 int와 float의 합집합인 number라는 TypeAlias를 만들 수 있습니다.

from typing import TypeAlias, Union

number: TypeAlias = Union[int, float]

매개변수를 자바스크립트 숫자로 접근합니다.

따라서 이 함수에 주석을 달기 위해

def multiplier(factor: number) -> Callable[[number], number]:
    def inner(value: number) -> inner:
        return value * factor
    return inner

a = multiplier(4.5)
a(3) #13.5

일반 함수

고전적인 일반 함수 예는

def pick(array, index):
    return array[index]

pick([1,2,3], 2) #3

TypeVar를 사용하면 이제 일반적인 장황한 내용을 생성할 수 있습니다(typescript보다 더 장황한).

from typing import TypeVar

T = TypeVar("T") # the argument and the name of the variable should be the same

그래서

from typing import TypeVar, Sequence

def pick(array: Sequence[T], index: int) -> T:
    return array[index]

print(pick([1,2,3,4], 2))

그렇다면 JavaScript에서 지도처럼 작동하는 사용자 정의 myMap 함수는 어떻습니까?

기억하세요: Python의 map()은 List 유형이 아닌 Iterable 유형을 반환합니다

def myMap(array, fn):
    return map(fn, array)

def twice(n): return n * 2
print(myMap([1,2,3], twice))

이 함수에 주석을 달기 위해 Callable 유형과 TypeVar 유형을 혼합하여 사용할 수 있습니다. 관찰...

from typing import TypeVar, Iterable, Callable

Input = TypeVar("Input")  # Input and "Input" must be the same
Output = TypeVar("Output")

def myMap(array: Iterable[Input], fn: Callable[[Input], Output]) -> Iterable[Output]:
    return map(fn, array)

def twice(n: int) -> int: return n * 2
print(myMap([1,2,3], twice))

또는 Callable 함수에 별칭을 지정할 수 있습니다

from typing import TypeVar, Iterable, Callable

Input = TypeVar("Input")
Output = TypeVar("Output")

MappableFunction = Callable[[Input], Output]

def myMap(array: Iterable[Input], fn: MappableFunction[Input, Output]) -> Iterable[Output]:
    return map(fn, array)

MappableFunction은 이러한 일반 유형 입력 및 출력을 가져와 Callable[[Input], Output]의 컨텍스트에 적용합니다.

myFilter 함수에 어떻게 주석이 추가될지 잠시 생각해 보세요.

이런 생각을 했다면

from typing import Iterable, TypeVar, Callable

Input = TypeVar("Input")

def myFilter(array: Iterable[Input], fn: Callable[[Input], bool]) -> Iterable[Input]:
    return filter(fn, array)

당신 말이 맞아요

일반 클래스

클래스 주석에 대해 이야기해서는 안 되지만 일반 클래스에 대해 설명할 시간을 좀 주세요.

Typescript-verse에서 왔다면 이렇게 정의했을 것입니다

class GenericStore<type>{
    stores: Array<type> = []

    constructor(){
        this.stores = []
    }

    add(item: Type){
        this.stores.push(item)
    }
}

const g1 = new GenericStore<string>(); //g1.stores: Array<string>
g1.add("Hello") //only string are allowed
</string></string></type></type>

그러나 Python에서는 다소 다르고 어색합니다.

  • 먼저 Generic 유형을 가져온 다음 이를 Generic 클래스의 하위로 만듭니다

이 GenericStore 클래스를 Python으로 다시 생성하려면

Callable[[argtype1, argtype2, argtype3], returnType]

Python에서 함수에 주석을 추가하는 방법을 배워야 하는 이유는 무엇입니까?

이전 블로그에서 말했듯이 이는 훨씬 더 스마트한 유형 시스템을 구축하는 데 도움이 되며 결과적으로 버그 발생 가능성을 줄여줍니다(특히 mypy와 같은 정적 파일 검사기를 사용할 때). 또한 강력한 유형 시스템을 사용하여 라이브러리(또는 SDK)를 작성할 때 라이브러리를 사용하는 개발자의 생산성을 약간 향상시킬 수 있습니다(주로 편집기 제안으로 인해)

궁금한 점이나 이 글에 틀린 부분이 있으면 댓글로 남겨주세요⭐

위 내용은 Python에서 함수에 주석 달기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 : 편집과 해석에 대한 깊은 다이빙파이썬 : 편집과 해석에 대한 깊은 다이빙May 12, 2025 am 12:14 AM

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

루프 대 파이썬의 루프 : 주요 차이점 설명루프 대 파이썬의 루프 : 주요 차이점 설명May 12, 2025 am 12:08 AM

forloopsareideal when

루프를위한 것 및 기간 : 실용 가이드루프를위한 것 및 기간 : 실용 가이드May 12, 2025 am 12:07 AM

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다May 12, 2025 am 12:05 AM

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

동일한 요소를 가진 Python Concatenate 목록동일한 요소를 가진 Python Concatenate 목록May 11, 2025 am 12:08 AM

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

해석 대 컴파일 언어 : Python 's Place해석 대 컴파일 언어 : Python 's PlaceMay 11, 2025 am 12:07 AM

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?May 11, 2025 am 12:05 AM

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.