<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: ViacheslavVoo</title>
    <description>The latest articles on DEV Community by ViacheslavVoo (@__d89cacba).</description>
    <link>https://dev.to/__d89cacba</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3408204%2F8d319295-ae53-437b-a867-03c564382db3.jpg</url>
      <title>DEV Community: ViacheslavVoo</title>
      <link>https://dev.to/__d89cacba</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/__d89cacba"/>
    <language>en</language>
    <item>
      <title>[Boost]</title>
      <dc:creator>ViacheslavVoo</dc:creator>
      <pubDate>Sun, 03 Aug 2025 09:40:17 +0000</pubDate>
      <link>https://dev.to/__d89cacba/-2ke9</link>
      <guid>https://dev.to/__d89cacba/-2ke9</guid>
      <description>&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f" class="crayons-story__hidden-navigation-link"&gt;Typing in Python: How Annotations Save Your Code and Speed Up Development&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/__d89cacba" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3408204%2F8d319295-ae53-437b-a867-03c564382db3.jpg" alt="__d89cacba profile" class="crayons-avatar__image"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/__d89cacba" class="crayons-story__secondary fw-medium m:hidden"&gt;
              ViacheslavVoo
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                ViacheslavVoo
                
              
              &lt;div id="story-author-preview-content-2749194" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/__d89cacba" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3408204%2F8d319295-ae53-437b-a867-03c564382db3.jpg" class="crayons-avatar__image" alt=""&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;ViacheslavVoo&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;Aug 3 '25&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f" id="article-link-2749194"&gt;
          Typing in Python: How Annotations Save Your Code and Speed Up Development
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/programming"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;programming&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/python"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;python&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/tutorial"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;tutorial&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/beginners"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;beginners&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
          &lt;a href="https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left"&gt;
            &lt;div class="multiple_reactions_aggregate"&gt;
              &lt;span class="multiple_reactions_icons_container"&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/exploding-head-daceb38d627e6ae9b730f36a1e390fca556a4289d5a41abb2c35068ad3e2c4b5.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/multi-unicorn-b44d6f8c23cdd00964192bedc38af3e82463978aa611b4365bd33a0f1f4f3e97.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/sparkle-heart-5f9bee3767e18deb1bb725290cb151c25234768a0e9a2bd39370c382d02920cf.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
              &lt;/span&gt;
              &lt;span class="aggregate_reactions_counter"&gt;5&lt;span class="hidden s:inline"&gt; reactions&lt;/span&gt;&lt;/span&gt;
            &lt;/div&gt;
          &lt;/a&gt;
            &lt;a href="https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              Comments


              &lt;span class="hidden s:inline"&gt;Add Comment&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            6 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;


</description>
      <category>programming</category>
      <category>python</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Typing in Python: How Annotations Save Your Code and Speed Up Development</title>
      <dc:creator>ViacheslavVoo</dc:creator>
      <pubDate>Sun, 03 Aug 2025 09:37:39 +0000</pubDate>
      <link>https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f</link>
      <guid>https://dev.to/__d89cacba/typing-in-python-how-annotations-save-your-code-and-speed-up-development-1o9f</guid>
      <description>&lt;p&gt;Python is a dynamically typed language. Is this good or bad? On one hand, it speeds up development: you don't need to declare or remember variable types. On the other hand, it can lead to errors that surface during runtime... or a month into production.  &lt;/p&gt;

&lt;p&gt;In this article, I'll show why type hinting is a tool that will save hours of debugging and make your code safer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's get started.
&lt;/h2&gt;

&lt;p&gt;Type annotations were first introduced in Python 3.5, released in 2015. Yet many developers still write code in the old style. Let's take a typical piece of code from a typical developer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def process_user_data(user_data):
    return user_data['name'].upper()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first glance, this appears to be a simple function with a reasonable name. But it hides several problems:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Opaque contract - without examining the implementation, it's impossible to understand:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;What data types are expected?&lt;/li&gt;
&lt;li&gt;What structure should user_data have?&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Fragility - it's unclear what the function will return in case of an error&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's improve the code and examine each element&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import TypedDict

class UserData(TypedDict):
    id: int
    name: str

def get_user_name(user_data: UserData) -&amp;gt; str:
    return user_data["name"].upper()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How Annotations Work:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Parameters: arg: type (e.g., user_data: UserData)&lt;/li&gt;
&lt;li&gt;Return value: -&amp;gt; return_type (in our case -&amp;gt; str)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Basic Types (Primitives)&lt;/strong&gt;&lt;br&gt;
The simplest and most commonly used annotations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from numbers import Real


def add(a: int, b: int) -&amp;gt; int:
  return a + b


def add(a: Real, b: Real) -&amp;gt; Real:
  return a + b


def greet(name: str) -&amp;gt; str:
  return f"Hello {name}"


def is_active(status: bool) -&amp;gt; bool:
  return status
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With type annotations, even the simplest functions become clearer and safer, as your IDE will warn you if you try to pass the wrong type.&lt;/p&gt;

&lt;p&gt;It's important to remember that your code will still run even with incorrectly passed values. Annotations only serve as hints for the developer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you want to learn more about AI and Python development, subscribe to my Telegram channel:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/+ir0CNH59B2UzMTAy" rel="noopener noreferrer"&gt;My channel&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Union, Optional, Literal&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Union allows specifying multiple valid types, for example, int/float.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import Union


def add(a: Union[int, float], b: Union[int, float]) -&amp;gt; Union[int, float]:
  return a + b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the add function accepts arguments of type int or float and returns a result of the same type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_element(d: dict[str, str], key: str) -&amp;gt; Union[str, None]:
  return d.get(key, None)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Optional indicates that a value can be either of type T or None. It is equivalent to Union[T, None].&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user_name: Optional[str] = None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Classes with optional fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User:
    def __init__(self, name: str, phone: Optional[str] = None):
        self.name = name
        self.phone = phone

user1 = User("Viacheslav", "+999999999")
user2 = User("Voo")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Literal strictly enforces allowed values. Ideal for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Statuses ("active", "pending", "completed")&lt;/li&gt;
&lt;li&gt;HTTP methods ("GET", "POST", "PUT")&lt;/li&gt;
&lt;li&gt;Any constant values
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HttpMethod = Literal["GET", "POST", "PUT", "DELETE"]

def send_request(method: HttpMethod, url: str) -&amp;gt; None:
    print(f"{method} запрос к {url}")

send_request("POST", "/api")  # OK
send_request("PATCH", "/")  # ERROR
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import Literal

def set_status(status: Literal["active", "inactive", "pending"]) -&amp;gt; None:
    print(f"Статус изменён на: {status}")

set_status("active")  # OK
set_status("deleted")  # ERROR
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Annotations for collections: lists, dictionaries, tuples&lt;/strong&gt;&lt;br&gt;
Python allows typing not only primitives but also complex data structures.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def find_item(d: dict[str, int], key: str) -&amp;gt; int | None:
  return d.get(key)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;TypedDict&lt;/strong&gt;&lt;br&gt;
TypedDict allows explicitly defining a dictionary structure:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Which keys are required&lt;/li&gt;
&lt;li&gt;What value types each key has
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import TypedDict

class ServerConfig(TypedDict):
  host: str
  port: int
  ssl: bool


def start_server(config: ServerConfig):
  print(f"Starting server with config: {config}")

config: ServerConfig  = {"host": "localhost", "port": 8080, "ssl": False}
start_server(config)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;TypedDict for Data Validation&lt;/strong&gt;&lt;br&gt;
Type annotations and typed structures work well for data validation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Book(TypedDict):
  title: str
  year: int


def validate_book(date: dict) -&amp;gt; Book:
  required_keys = {"title", "year"}

  if not all(key in data for key in required_keys):
    return None
  return Book(**data)

raw_data  = {"title": "Python", "year": 2005}
book: Book | None  = validate_book(raw_data)

if book:
  print(book["title"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;NamedTuple&lt;/strong&gt;&lt;br&gt;
Tuples are convenient for storing immutable data, such as DTOs. However, accessing fields by indices ([0], [1]) is unreliable and makes code harder to read. NamedTuple solves this problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import NamedTuple


class Product(NamedTuple):
  name: str
  price: int
  quantity: int


def total_value(product: Product) -&amp;gt; int:
  return product.price * product.quantity
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Callable, Generator&lt;/strong&gt;&lt;br&gt;
Functions also support annotations. This is useful for higher-order functions, callbacks, and generators. Let's write a function that accepts other functions (with specific arguments) as parameters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def send_messages(on_success: Callable[[], None]), 
                  on_failure: Callable[[Exception], None],
                  ) -&amp;gt; None:
      if random.random() &amp;lt; 0.5:
        return on_success()
      return on_failure(Exception('something went wrong'))


def on_success() -&amp;gt; None:
  print("success")


def on_failure(exception: Exception) -&amp;gt; None:
  print(exception)


send_messages(on_success, on_failure)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The annotation for generators looks like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;YieldType– the type of value the generator yields via yield&lt;/li&gt;
&lt;li&gt;SendType – the type of value passed into the generator via send&lt;/li&gt;
&lt;li&gt;ReturnType – the type of value returned upon generator completion
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import Generator 


def generator(words: list[str]) -&amp;gt; Generator[str, None, None]:
  for word in words:
    yield word


words  = ["Москва", "Питер", "Казань"]

for word in word_generator(words):
    print(word)   
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Generics
&lt;/h2&gt;

&lt;p&gt;Suppose we want to create a function that returns the first element of a list of any type. Without generics, you would have to use the Any annotation, which would be useless.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import TypeVar


T  = TypeVar("T")


def get_first_element(lst: list[T]) -&amp;gt; T | None:
  return lst[0] if lst else None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's implement a stack that holds values of a single type using Generics:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Stack(Generic[T]):
  def __init__(self):
    self.stack: list[T] = []


  def push(self, element: T) -&amp;gt; None:
    self.stack.append(element)

  def pop(self) -&amp;gt; T:
    return self.stack.pop()


  int_stack  = Stack[int]()
  int_stack.push(1)
  int_stack.push("1") 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Custom Annotations (TypeAlias, NewType, Protocol)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;TypeAlias&lt;/strong&gt;&lt;br&gt;
Useful when we need to describe a complex annotation that isn't a data structure and takes up too much space. For example, when writing a type annotation for a function, as in one of the examples above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import TypeAlias, Callable 


func: TypeAlias  = Callable[[float, float], float]

def apply_operation(a: float, b: float, op: func) -&amp;gt; float:
  return op(a, b)


add_op: func  = lambda x, y: x + y
print(apply_operation(1.2, 2.5, add))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without TypeAlias, the function signature would look cumbersome.&lt;/p&gt;

&lt;p&gt;You can also use TypeAlias for recursive references—for example, when annotating JSON-like structures that differ from Python's native types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import TypeAlias, Union

Json: TypeAlias = Union[
    str, int, float, bool, None,
    dict[str, 'Json'],  # рекурсивная ссылка
    list['Json']
]


def parse_json(data: Json) -&amp;gt; None:
    print(data)


data: Json = {
    "name": "ViacheslavVoo",
    "scores": [95, 87, 91],
    "metadata": {"active": True, "tags": None},
}

parse_json(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here it's worth noting that the IDE may not show an error if incorrect types are used. To validate complex or recursive annotations, it's best to use mypy, which will detect type mismatches.&lt;/p&gt;

&lt;p&gt;For example, if you mistakenly use tuple instead of dict in a JSON-like structure, mypy will raise an error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: Dict entry 0 has incompatible type "str": "tuple[int, int, int]"; expected "str": "str | int | float | dict[str, Json] | list[Json] | None"  [dict-item]
Found 1 error in 1 file (checked 1 source file)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;NewType&lt;/strong&gt;&lt;br&gt;
This type of annotation should be used when you need to create a distinct new type based on an existing one. The key difference from other annotations is that NewType enforces type separation—meaning NewType('X', int) != int, unlike TypeAlias.&lt;/p&gt;

&lt;p&gt;This makes it useful for semantic differentiation, ensuring that values of the same underlying type (like int) are not accidentally mixed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import NewType

UserId  = NewType("UserId", int)
OrderId  = NewType("OrderId", int)


def get_user(UserId) -&amp;gt; None:
  ...


user_id  = UserId(1)
order_id  = OrderId(1)

get_user(user_id)
get_user(order_id) #mypy покажет ошибку, так как UserId и OrderId  - разные типы
get_user(1) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Before Python 3.10, NewType was a zero-overhead abstraction (erased at runtime).&lt;/li&gt;
&lt;li&gt;In Python 3.10, it became a wrapper class, adding minor runtime overhead.&lt;/li&gt;
&lt;li&gt;Python 3.11+ restored performance to pre-3.10 levels (near-zero cost).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Protocol&lt;/strong&gt;&lt;br&gt;
The Protocol can be used when creating interfaces that you do not want to explicitly implement or cannot inherit from. Any class that has a draw method will conform to the Protocol. This feature is extremely useful for testing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import Protocol


class Drawable(Protocol):
    def draw(self) -&amp;gt; None:
        ...


class Circle:
    def draw(self) -&amp;gt; None:
        print("draw circle")

    def some_func(self):
        print("some_func")


def render(obj: Drawable):
    obj.draw()


render(Circle())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Typing in Python is not about strict constraints but a way to make code clearer, more reliable, and more convenient. Use type hinting in your projects—it will save you hours of refactoring and spare the nerves of new team members maintaining your code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thanks for reading!&lt;/strong&gt;&lt;br&gt;
Follow me on Telegram to stay updated on new articles.&lt;br&gt;
&lt;a href="https://t.me/+ir0CNH59B2UzMTAy" rel="noopener noreferrer"&gt;My channel&lt;/a&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
