Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2024 Jim Chng <jimchng@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

1. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

2. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ test-leak:
test-file:
$(PYTHON) -m pytest $(FILE) $(PYTEST_FLAGS)

test-e2e:
bash tests/build_test_pyvers_docker_images.sh

# Development workflow targets
dev: clean build test

Expand Down
20 changes: 18 additions & 2 deletions examples/email_str.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import pytest


import re

import pytest

from newtype import NewType, newtype_exclude


class EmailStr(NewType(str)):
# you can define `__slots__` to save space
__slots__ = (
'_local_part',
'_domain_part',
)

def __init__(self, value: str):
super().__init__(value)
super().__init__()
if "@" not in value:
raise TypeError("`EmailStr` requires a '@' symbol within")
self._local_part, self._domain_part = value.split("@")
Expand Down Expand Up @@ -98,6 +106,14 @@ def test_emailstr_properties_methods():
assert EmailStr.is_valid_email("invalid-email.com") is False


def test_email_str__slots__():
email = EmailStr("test@example.com")

with pytest.raises(AttributeError):
email.hi = "bye"
assert email.hi == "bye"


# Run the tests
if __name__ == "__main__":
pytest.main([__file__])
Binary file added examples/email_str_def.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/email_str_init.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/email_str_replace.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 43 additions & 13 deletions newtype/newtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,18 @@ def func_is_excluded(func):
return getattr(func, NEWTYPE_EXCLUDE_FUNC_STR, False)


def can_subclass_have___slots__(base_type: T) -> bool:
try:

class _Test(base_type): # type: ignore[valid-type, misc]
__slots__ = ("a", "b")

_Test()
except TypeError:
return False
return True


def NewType(base_type: T, **context: "Dict[str, Any]") -> T: # noqa: N802, C901
"""Create a new type that preserves type information through all operations.

Expand Down Expand Up @@ -175,6 +187,12 @@ class BaseNewType(base_type): # type: ignore[valid-type, misc]
NEWTYPE_INIT_ARGS_STR,
NEWTYPE_INIT_KWARGS_STR,
)
else:
if can_subclass_have___slots__(base_type):
__slots__ = (
NEWTYPE_INIT_ARGS_STR,
NEWTYPE_INIT_KWARGS_STR,
)

def __init_subclass__(cls, **context) -> None:
"""Initialize a subclass of BaseNewType.
Expand All @@ -190,8 +208,9 @@ def __init_subclass__(cls, **context) -> None:
**context: Additional context for subclass initialization
"""
super().__init_subclass__(**context)
NEWTYPE_LOGGER.debug(f"cls: {cls}")
NEWTYPE_LOGGER.debug(base_type, base_type.__dict__)
NEWTYPE_LOGGER.debug("cls.__dict__: ", cls.__dict__)
NEWTYPE_LOGGER.debug(f"cls.__dict__: {cls.__dict__}")

constructor = cls.__init__
original_cls_dict = {}
Expand All @@ -201,19 +220,18 @@ def __init_subclass__(cls, **context) -> None:
for k, v in base_type.__dict__.items():
if callable(v) and (k not in object.__dict__) and (k not in original_cls_dict):
NEWTYPE_LOGGER.debug(
"callable(v) and (k not in object.__dict__) and \
(k not in original_cls_dict) ; k: ",
k,
f"callable(v) and (k not in object.__dict__) and \
(k not in original_cls_dict) ; k: {k}"
)
setattr(cls, k, NewTypeMethod(v, base_type))
elif k not in object.__dict__:
if k == "__dict__":
continue
setattr(cls, k, v)
NEWTYPE_LOGGER.debug("Set")
NEWTYPE_LOGGER.debug("original_cls_dict: ", original_cls_dict)
NEWTYPE_LOGGER.debug(f"original_cls_dict: {original_cls_dict}")
for k, v in original_cls_dict.items():
NEWTYPE_LOGGER.debug("k in original_cls_dict: ", k)
NEWTYPE_LOGGER.debug(f"k in original_cls_dict: {k}")
if (
callable(v)
and k != "__init__"
Expand All @@ -228,10 +246,23 @@ def __init_subclass__(cls, **context) -> None:
NEWTYPE_LOGGER.debug("Set")
NEWTYPE_LOGGER.debug("Setting cls.__init__")
cls.__init__ = NewTypeInit(constructor) # type: ignore[method-assign]
if hasattr(cls, "__slots__"):
NEWTYPE_LOGGER.debug("cls.__slots__: ", cls.__slots__)
NEWTYPE_LOGGER.debug("Setting cls.__init__ completed")
NEWTYPE_LOGGER.debug("cls.__dict__: ", cls.__dict__, " at end of __init_subclass__")
# if hasattr(cls, "__slots__"):
# NEWTYPE_LOGGER.debug(f"cls.__slots__: {cls.__slots__}")
# BaseNewType.__slots__ = (
# *(base_type.__slots__ if hasattr(base_type, "__slots__") else ()),
# *cls.__slots__,
# NEWTYPE_INIT_ARGS_STR,
# NEWTYPE_INIT_KWARGS_STR,
# )
# NEWTYPE_LOGGER.debug(
# f"cls.__slots__: {cls.__slots__}, at end of `__init_subclass__`"
# )
# NEWTYPE_LOGGER.debug(f"cls.__dict__: {cls.__dict__}, at end of `__init_subclass__`")
if hasattr(BaseNewType, "__slots__"):
NEWTYPE_LOGGER.debug(
f"BaseNewType.__slots__: {BaseNewType.__slots__}, at end of `__init_subclass__`"
)

def __new__(cls, value=None, *_args, **_kwargs):
"""Create a new instance of BaseNewType.
Expand All @@ -244,7 +275,6 @@ def __new__(cls, value=None, *_args, **_kwargs):
*_args: Additional positional arguments
**_kwargs: Additional keyword arguments
"""
NEWTYPE_LOGGER.debug("cls, cls.__new__: ", cls, cls.__new__)
if base_type.__new__ == object.__new__:
NEWTYPE_LOGGER.debug(
"base_type.__new__ == object.__new__; base_type.__new__ = ", base_type.__new__
Expand Down Expand Up @@ -272,9 +302,9 @@ def __new__(cls, value=None, *_args, **_kwargs):
if v is not UNDEFINED:
setattr(inst, k, v)
else:
NEWTYPE_LOGGER.debug(
"base_type.__new__ != object.__new__; base_type.__new__ = ", base_type.__new__
)
# NEWTYPE_LOGGER.debug(
# "base_type.__new__ != object.__new__; base_type.__new__ = ", base_type.__new__
# )
inst = cast("BaseNewType", base_type.__new__(cls, value))
return inst

Expand Down
Loading
Loading