Hey everyone! I’m beyond excited to share python-newtype
, a new Python C-extension library I’ve been working on that makes Domain-Driven Development (DDD) not only easier but also super fast!
Here’s what makes python-newtype
stand out: It’s built with a C-extension under the hood, which means it’s optimized for performance. While you get all the flexibility of Python’s dynamic typing and extensibility, the C-extension ensures that method calls and type wrapping are lightning-fast. If you’ve ever felt that Python’s type-heavy libraries slow things down, you’re going to love this!
One of the coolest features is how python-newtype
handles methods of the supertype. If a method from the supertype returns an instance of the supertype, python-newtype
automatically converts it to an instance of the subtype. Thanks to the C-extension, this process is super-efficient, with almost no overhead compared to normal Python method calls.
Here’s an example of how it works:
from newtype import NewType
class EnhancedStr(NewType(str)):
def reverse(self):
return self[::-1]
text = EnhancedStr("Hello World")
# Use a standard string method that returns an instance of the supertype
upper_text = text.upper() # This normally returns a `str`
# But with `python-newtype`, it’s automatically converted to `EnhancedStr`
print(isinstance(upper_text, EnhancedStr)) # True
print(upper_text.reverse()) # "DLROW OLLEH"
Even though .upper()
is a method from str
, its return value is automatically converted to EnhancedStr
—and the C-extension makes this transformation incredibly fast. You get type invariance without sacrificing performance.
Why the C-extension? Python’s dynamic type system is powerful, but when you start wrapping and intercepting methods, performance can take a hit. By implementing the core logic in C, python-newtype
minimizes the overhead involved in type conversions and method interceptions, making it ideal for production environments where speed matters.
This library is perfect for building domain-specific models where you want to extend existing types with additional logic while preserving their behavior. It’s also memory-efficient, thanks to the use of weak references for caching.
You can try it out now with:
pip install python-newtype
I’d love for you to check it out and let me know what you think! Whether you’re into clean code, type safety, or just love Python, this library has something for everyone.
Full documentation is available here [https://py-nt.asyncmove.com/]
Check out the PYPI and GitHub in the Comments section!
Thanks for reading, and happy coding!