{"id":31747,"date":"2024-11-01T09:02:26","date_gmt":"2024-11-01T09:02:26","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=31747"},"modified":"2024-11-01T11:48:26","modified_gmt":"2024-11-01T11:48:26","slug":"python-type-annotation","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/31747\/","title":{"rendered":"python type annotation"},"content":{"rendered":"\n<p>Python is well known as a dynamic typing language. This means that every value is checked at runtime without the need to explicitly specify the type of a variable. However, as large projects become more complex and multiple developers collaborate, understanding and maintaining the code can become difficult. To address this, <strong>Type Annotation<\/strong> was introduced in Python 3.5. Using type annotations helps improve code readability, prevent bugs, and enhance autocompletion features.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Basics of Type Annotation<\/h2>\n\n\n\n<p>Type annotation is the syntax that allows explicitly specifying the types of variables or functions. Here are the basic ways to annotate the types of variables and functions:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Variable Annotation:\nx: int = 10\ny: float = 10.5\nname: str = \"Alice\"\n\nFunction Annotation:\ndef greeting(name: str) -&gt; str:\n    return \"Hello \" + name\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">1.1 Type Annotation of Variables<\/h3>\n\n\n\n<p>By specifying the type of a variable, the code writer can clearly indicate which type is expected. This allows for early error detection through static analysis in tooling and IDEs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1.2 Annotations for Function Parameters and Return Values<\/h3>\n\n\n\n<p>Function annotations can explicitly specify the input and output types of a function, helping to anticipate what type of data the function will receive. This is very helpful during code reviews.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Built-in Data Types<\/h2>\n\n\n\n<p>Python supports various built-in data types, and these types can be used in annotations.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Basic types like int, float, str, bool, None, etc.<\/li>\n\n\n\n<li>Container types like List, Dict, Set, Tuple can be further refined using the <strong>typing<\/strong> module.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>from typing import List, Dict, Tuple\n\nnames: List&#91;str] = &#91;\"Alice\", \"Bob\", \"Charlie\"]\nscores: Dict&#91;str, int] = {\"Alice\": 95, \"Bob\": 85}\nposition: Tuple&#91;int, int] = (10, 20)\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">3. Union and Optional<\/h2>\n\n\n\n<p>When multiple types are allowed, it is common to use <code>Union<\/code>, and when None is allowed, <code>Optional<\/code> is used.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from typing import Union, Optional\n\nvalue: Union&#91;int, float] = 5.5\n\ndef get_user(id: int) -&gt; Optional&#91;Dict&#91;str, str]]:\n    if id == 1:\n        return {\"name\": \"Alice\", \"role\": \"admin\"}\n    return None\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">4. User-defined Types<\/h2>\n\n\n\n<p>When you need to define complex types, using <code>Type<\/code> or <code>NewType<\/code> allows you to write clearer code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from typing import NewType\n\nUserID = NewType('UserID', int)\nadmin_user_id: UserID = UserID(524313)\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4.1 Type Alias<\/h3>\n\n\n\n<p>Using type aliases allows you to express complex type structures with concise names.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Vector = List&#91;float]\n\ndef normalize(vec: Vector) -&gt; Vector:\n    magnitude = sum(x**2 for x in vec) ** 0.5\n    return &#91;x \/ magnitude for x in vec]\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">5. Generic Types<\/h2>\n\n\n\n<p>Using generic types allows a single function or class to work with multiple types. You can define generic types using the <code>typing.Generic<\/code> class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass Box(Generic&#91;T]):\n    def __init__(self, content: T) -&gt; None:\n        self.content = content\n\nint_box = Box(123)\nstr_box = Box(\"hello\")\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">6. Advanced Example<\/h2>\n\n\n\n<p>Here is a slightly more complex example utilizing type annotations.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from typing import List, Dict, Union, Callable\n\ndef process_data(data: List&#91;Union&#91;int, float, str]]) -&gt; Dict&#91;str, Union&#91;int, float]]:\n    result: Dict&#91;str, Union&#91;int, float]] = {'total': 0, 'numeric_count': 0}\n\n    def is_number(val: Union&#91;int, float, str]) -&gt; bool:\n        return isinstance(val, (int, float))\n\n    for item in data:\n        if is_number(item):\n            result&#91;'total'] += item  # Prevents type warnings.\n            result&#91;'numeric_count'] += 1\n\n    return result\n\nmixed_data: List&#91;Union&#91;int, float, str]] = &#91;10, '20', 30.5, 'forty', '60', 70.2]\noutput = process_data(mixed_data)\nprint(output)\n# {'total': 110.7, 'numeric_count': 3}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">7. Static Type Checking Tools<\/h2>\n\n\n\n<p>Type annotations are most useful when used with static type checking tools. In Python, tools like <strong>mypy<\/strong>, <strong>Pyright<\/strong>, and <strong>Pylance<\/strong> are widely used.<\/p>\n\n\n\n<p>For example, <code>mypy<\/code> is used as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mypy script.py<\/code><\/pre>\n\n\n\n<p>These tools are very effective in checking the type consistency of the code and preventing unexpected type errors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">8. Conclusion<\/h2>\n\n\n\n<p>Type annotation is a powerful feature of Python that greatly helps improve code readability, ease maintenance, and prevent errors early. Additionally, when combined with static analysis tools, it provides greater stability for large projects. Through this tutorial, I hope you will be able to effectively utilize type annotations and write more robust Python code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python is well known as a dynamic typing language. This means that every value is checked at runtime without the need to explicitly specify the type of a variable. However, as large projects become more complex and multiple developers collaborate, understanding and maintaining the code can become difficult. To address this, Type Annotation was introduced &hellip; <a href=\"https:\/\/atmokpo.com\/w\/31747\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;python type annotation&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[98],"tags":[95],"class_list":["post-31747","post","type-post","status-publish","format-standard","hentry","category--en","tag--en"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>python type annotation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/31747\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"python type annotation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Python is well known as a dynamic typing language. This means that every value is checked at runtime without the need to explicitly specify the type of a variable. However, as large projects become more complex and multiple developers collaborate, understanding and maintaining the code can become difficult. To address this, Type Annotation was introduced &hellip; \ub354 \ubcf4\uae30 &quot;python type annotation&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/31747\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:02:26+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:48:26+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"3\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/31747\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/31747\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"python type annotation\",\"datePublished\":\"2024-11-01T09:02:26+00:00\",\"dateModified\":\"2024-11-01T11:48:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/31747\/\"},\"wordCount\":412,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"keywords\":[\"\ud30c\uc774\uc36c\uac15\uc88c\"],\"articleSection\":[\"Python Study\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/31747\/\",\"url\":\"https:\/\/atmokpo.com\/w\/31747\/\",\"name\":\"python type annotation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:02:26+00:00\",\"dateModified\":\"2024-11-01T11:48:26+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/31747\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/31747\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/31747\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"python type annotation\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"python type annotation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/31747\/","og_locale":"ko_KR","og_type":"article","og_title":"python type annotation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Python is well known as a dynamic typing language. This means that every value is checked at runtime without the need to explicitly specify the type of a variable. However, as large projects become more complex and multiple developers collaborate, understanding and maintaining the code can become difficult. To address this, Type Annotation was introduced &hellip; \ub354 \ubcf4\uae30 \"python type annotation\"","og_url":"https:\/\/atmokpo.com\/w\/31747\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:02:26+00:00","article_modified_time":"2024-11-01T11:48:26+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"3\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/31747\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/31747\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"python type annotation","datePublished":"2024-11-01T09:02:26+00:00","dateModified":"2024-11-01T11:48:26+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/31747\/"},"wordCount":412,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"keywords":["\ud30c\uc774\uc36c\uac15\uc88c"],"articleSection":["Python Study"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/31747\/","url":"https:\/\/atmokpo.com\/w\/31747\/","name":"python type annotation - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:02:26+00:00","dateModified":"2024-11-01T11:48:26+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/31747\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/31747\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/31747\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"python type annotation"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/31747","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=31747"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/31747\/revisions"}],"predecessor-version":[{"id":31748,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/31747\/revisions\/31748"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=31747"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=31747"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=31747"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}