Skip to content

Request: remove type constraints #492

@mjr129

Description

@mjr129

I'd like to create a PEP-484-style function annotation.

Like other annotations, my annotation:

  • serves to document my code
  • can be accessed at run-time via reflection (i.e. the inspect library).
  • is irrelevant as far as the function itself is concerned

Let's call my annotation MoreThan, and say I can use it like so:

def make_booking(people : MoreThan[int, 5]) -> None:
    assert isinstance(people, int), "Unexpected type"
    assert people > 5, "Not enough people"
    ...

MoreThan is a very simple class:

class MoreThan:
    def __init__(self, type_ : type = None, minimum : int = None):
        self.type    = type_
        self.minimum = minimum

    def __getitem__(self, item : Tuple[type, int]):
        return MoreThan( item[0], item[1] )

And so all works hunky-dory, until I try to mix this with other PEP-484 annotations like:

def make_booking(people : Optional[MoreThan[int, 5]] = None) -> None:
...

This fails, because Optional/Union won't accept non-type parameters.

This can obviously be fixed by deriving MoreThan from type, or using my own version of Optional, but these add a big overhead, and feel like a bit of a hack considering MoreThan isn't actually instantiable.

It would be nice if the typing library either supported non-type derived annotations, or, if not possible, provided a simple mechanism for custom annotations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions