Writing a stub file for a PyO3 module

Hi,

i am currently trying to write a .pyi file for a small PyO3 library.

Specifically this function here: demoparser/src/python/src/lib.rs at main · LaihoE/demoparser · GitHub

It takes WantedPropState but does not expose these as an importable type. A user can pass anything that fits this protocol:

_PyVariant = Union[bool, str, int, float]
class _WantedPropState(Protocol):

    prop: str
    state: _PyVariant

But if i define that in the stub file then any type checker will allow a user to import these types. Is there any way around this from just the python/stub side?

Cheers

I’m not too familiar with the workings of PyO3 so I don’t know by looking if this is actually importable but supposed to be private or if trying to import it fails.

If the type actually isn’t importable at runtime I believe you can mark it with @typing.type_check_only in the .pyi file to indicate that the class is not usable by the user at runtime and type checkers should understand this.

1 Like

Ah, thanks a ton! That is exactly it.

The original implementation with PyO3 here is that the class is not importable at all but can be created from any python object with the required attributes, so i needed to define a protocol that states that without users expecting to be able to import that protocol class.