Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python bindings generate invalid class hierarchy for foreign traits #2264

Closed
mhammond opened this issue Oct 10, 2024 · 0 comments
Closed

Python bindings generate invalid class hierarchy for foreign traits #2264

mhammond opened this issue Oct 10, 2024 · 0 comments

Comments

@mhammond
Copy link
Member

Best demonstrated with this patch:

--- a/fixtures/proc-macro/tests/bindings/test_proc_macro.py
+++ b/fixtures/proc-macro/tests/bindings/test_proc_macro.py
@@ -25,11 +25,13 @@
 assert(rename_test())
 
 trait_impl = obj.get_trait(None)
+assert isinstance(trait_impl, Trait)
 assert trait_impl.concat_strings("foo", "bar") == "foobar"
 assert obj.get_trait(trait_impl).concat_strings("foo", "bar") == "foobar"
 assert concat_strings_by_ref(trait_impl, "foo", "bar") == "foobar"
 
 trait_impl2 = obj.get_trait_with_foreign(None)
+assert isinstance(trait_impl2, TraitWithForeign)
 assert trait_impl2.name() == "RustTraitImpl"
 assert obj.get_trait_with_foreign(trait_impl2).name() == "RustTraitImpl"

which causes the second addition to fail: TypeError: Instance and class checks can only be used with @runtime_checkable protocols

To understand the problem, first consider how traits without with-foreign are generated:

class TraitProtocol(typing.Protocol):
    ...

class Trait:
    _pointer: ctypes.c_void_p
    ...

which seems correct - Trait (the name of the object) does not derive from typing.Protocol - protocols are used only by type checkers rather than at runtime.

However, consider foreign traits:

class TraitWithForeign(typing.Protocol):
    ...

class TraitWithForeignImpl:
    _pointer: ctypes.c_void_p

here, TraitWithForeign (the name of the object) does derive from typing.Protocol - hence the is_instance check fails.

While it would be possible to allow this to work by opting-in to runtime checks for these protocols, I think we should do the "correct" thing and arrange to generate a class hierarchy that does what the typing docs recommend.

Part of explaining why we do this is apparently this comment - ISTM that it might be fine to relax this a little, and just support typing.Protocol in all cases.

mhammond added a commit to mhammond/uniffi-rs that referenced this issue Oct 11, 2024
mhammond added a commit to mhammond/uniffi-rs that referenced this issue Oct 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant