Skip to content

Protocol checking against typing_extenstion.Protocol fails #479

@iliapolo

Description

@iliapolo

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

Typeguard version

4.3.0

Python version

Python 3.10.4

What happened?

Expected typeguard to ignore private attributes of the typing_extension.Protocol so that type checking would pass.

Note: Honestly this was my first intuition, but I realize it might be out of scope as I'm not sure what your stance is with respect to supporting the typing_extensions package. Perhaps this issue is more a feature request to allow configuring custom attributes that typeguard will ignore when typechecking protocols.

How can we reproduce the bug?

import typing_extensions
import builtins
import typeguard

class IDo(typing_extensions.Protocol):
    def do_something(self) -> builtins.str:
        ...

def doer(do: IDo) -> builtins.str:
    typeguard.check_type(value=do, expected_type=IDo)
    return do.do_something()

class DefaultDo:
    def do_something(self) -> builtins.str:
        return "did something"
    
print(doer(DefaultDo()))

Running the above program will result in:

typeguard.TypeCheckError: __main__.DefaultDo is not compatible with the IDo protocol because it has no attribute named '__protocol_attrs__'

Indeed, extending the typing_extensions.Protocol adds the __protocol_attrs__ attribute and causes the mismatch. I did notice however that typeguard has provisions to ignore private attributes of the typing.Protocol class:

ignored_attrs = set(dir(typing.Protocol)) | {
"__annotations__",
"__non_callable_proto_members__",
}

So I was thinking this might be extended to support typing_extension.Protocol? If not, it would be great if we had some way to inject custom attributes we'd like typeguard to ignore.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions