Skip to content

Instantly share code, notes, and snippets.

@TimonLukas
Last active August 13, 2023 23:14
Show Gist options
  • Save TimonLukas/21a4c7c8fc9cca48a3236f10793accc0 to your computer and use it in GitHub Desktop.
Save TimonLukas/21a4c7c8fc9cca48a3236f10793accc0 to your computer and use it in GitHub Desktop.
Python nominal typing (with beartype)
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)
@TimonLukas
Copy link
Author

TimonLukas commented Aug 13, 2023

$> python3 test-int-subclass.py
### Try both with int function
process_int_without(5 [type=<class 'int'>])
process_int_without(6 [type=<class '__main__.MyInt'>])

### Try both with MyInt function
process_myint_without(5 [type=<class 'int'>])
process_myint_without(6 [type=<class '__main__.MyInt'>])

### Try both with beartype int function
process_int_with(5 [type=<class 'int'>])
process_int_with(6 [type=<class '__main__.MyInt'>])

### Try both with beartype MyInt function
process_myint_with(5 [type=<class 'int'>]) errored as expected: Function __main__.process_myint_with() parameter bar=5 violates type hint <class '__main__.MyInt'>, as int 5 not instance of <protocol "__main__.MyInt">.
process_myint_with(6 [type=<class '__main__.MyInt'>])

### Starting tests with type-cast value
process_myint_with(5 [type=<class 'int'>]) errored as expected: Function __main__.process_myint_with() parameter bar=6 violates type hint <class '__main__.MyInt'>, as int 6 not instance of <protocol "__main__.MyInt">.
process_myint_without(6 [type=<class 'int'>])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment