Allow mulitple type constraints

Sometimes, I want an argument to satisfy more than one type constraints. For example, below, the function requires module to be an instance of torch.nn.Module (the base class for all PyTorch neural network modules), but it also requires the module to have a method with a specific signature. Unfortunately, creating a subclass and requiring subclassing is not an option. So, I propose introducing the “&” operator for types:

from typing import Protocol
import torch
import torch.nn


class SimpleModule(Protocol):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        ...


def apply_module(
    module: torch.nn.Module & SimpleModule,
    x: torch.Tensor
) -> torch.Tensor:
    return module(x)
1 Like

It sounds like what you’re looking for is an “Intersection” type: Introduce an Intersection · Issue #213 · python/typing · GitHub.

6 Likes

Thanks for pointing to this!

2 Likes

For me the discussion in the issue is very confusing or did I understand it wrong?

The issue was opened as “Introduce an Intersection” while the introductory example (and most of the discussion) talks about union of the class attributes, not intersection.

Edit: Ok, after longer thinking I guess I got it:

  • A — set of classes which have attributes a, b (and possibly other attributes)
  • B — set of classes which have attributes c, d (and possibly other attributes)
  • C — set of classes from A and B which have attributes a, b, c, d (and possibly other attributes)

C is intersection of A and B.

I was looking at it from the other side :slight_smile:

2 Likes