Create Custom New Types in Python

preview_player
Показать описание
In this video we learn how to create custom new types in Python, using the NewType class.

◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚

💼 Services 💼

🌐 Social Media & Contact 🌐
Рекомендации по теме
Комментарии
Автор

After switching from Python to C# I must admit that strong static typing is a life saver and don't want to go back. Dynamic programming languages are good for scripting but if you want to build serious apps you will notice that capturing silly mistakes at design time is better than capturing them at runtime.

agailloty
Автор

would be great if you gave us more info, at least in the description man! What version of python are you using? 3.12? 3.13? 3.10?!

MrEo
Автор

Wouldn’t it be easier to create a (data)class for this?

arnoudstolk
Автор

Going AWESOME!... and going and going...

GuillermoGarcia
Автор

A good type library would be able to convert bar to pascal or lbs to Newtons.

pnachtwey
Автор

I would have expected an example of code that combines runtime validation and type checking:
from typing import NewType

# Define the NewType for ZipCode
ZipCode = NewType('ZipCode', int)

# Create a class to handle the validation and encapsulation
class ZipCodeClass:
def __init__(self, code: ZipCode):
if not self._is_valid_zip(code):
raise ValueError("ZipCode must be a 5-digit number")
self._code = code

def _is_valid_zip(self, code: int) -> bool:
return 10000 <= code <=

@property
def code(self) -> ZipCode:
return self._code

def __repr__(self):
return f"ZipCode({self._code})"

def __str__(self):
return str(self._code)

# Usage example
try:
z = ZipCodeClass(ZipCode(12345))
print(z)
except ValueError as e:
print(e)

EliSpizzichino
Автор

Probably you said that one anywhere in video but I couldn't notice. Why we need this in python? Or we need that?

arda
Автор

so the best way to make new types like say imaginary/complex numbers is define it as a class

vishnubalaji
Автор

That's not a very good example new type. Zip codes are represented by 5 numeric digit characters, or 5 num digits, a hyphen, then 4 num digits, and the first integer is always left-padded with zeroes. If the ZipCode type implemented these requirements, then it might be useful. Otherwise it's just a synonym for a native type, which only adds unnecessary complexity without adding any useful new functionality.

IronTeddyBear
Автор

New type is only when created new class.

zj
Автор

You forgot to talk about Newtype with object 🙄

kmano
Автор

Good Lord, ZIP Codes are strings, not integers. You can’t meaningfully add or subtract them, and if your ZIP Code starts with zero, you sure as heck better not drop it as you would storing it as an integer.

NickDanger
Автор

How to use torspy pip package
How to hackers spy DarkWeb?

animelover