Last active
August 13, 2023 23:14
-
-
Save TimonLukas/21a4c7c8fc9cca48a3236f10793accc0 to your computer and use it in GitHub Desktop.
Python nominal typing (with beartype)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from beartype import beartype | |
class MyInt(int): | |
... | |
def process_int_without(bar: int): | |
print(f"process_int_without({bar} [type={type(bar)}])") | |
def process_myint_without(bar: MyInt): | |
print(f"process_myint_without({bar} [type={type(bar)}])") | |
@beartype | |
def process_int_with(bar: int): | |
print(f"process_int_with({bar} [type={type(bar)}])") | |
@beartype | |
def process_myint_with(bar: MyInt): | |
print(f"process_myint_with({bar} [type={type(bar)}])") | |
foo_int: int = 5 | |
foo_myint: MyInt = MyInt(6) | |
print("### Try both with int function") | |
process_int_without(foo_int) | |
process_int_without(foo_myint) | |
print("\n### Try both with MyInt function") | |
process_myint_without(foo_int) | |
process_myint_without(foo_myint) | |
print("\n### Try both with beartype int function") | |
process_int_with(foo_int) | |
process_int_with(foo_myint) | |
print("\n### Try both with beartype MyInt function") | |
try: | |
process_myint_with(foo_int) | |
print("no error?") | |
except Exception as e: | |
print(f"process_myint_with({foo_int} [type={type(foo_int)}]) errored as expected: {e}") | |
process_myint_with(foo_myint) | |
print("\n### Starting tests with type-cast value") | |
foo_myint_to_int = int(foo_myint) | |
# Try both with beartype MyInt function | |
try: | |
process_myint_with(foo_myint_to_int) | |
print("no error?") | |
except Exception as e: | |
print(f"process_myint_with({foo_int} [type={type(foo_int)}]) errored as expected: {e}") | |
process_myint_without(foo_myint_to_int) |
Author
TimonLukas
commented
Aug 13, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment