21

After seeing the (awesome) new Annotated type annotation in python 3.9 (varaidic type constraints!), I rushed to upgrade so I could check them out. (https://docs.python.org/3/library/typing.html?highlight=valuerange)

But when I tried using ValueRange[min,max] or MaxLen[n] - I couldn't seem to find them anywhere.. PyCharm didn't offer me any help, and they don't seem to be in the typing module where I might expect them.

The docs feature them but googling I can't find any reference online as to how to actually import them.

Are they not in the language yet? or just in some new module I'm not aware of?

Jonathan Levin
  • 594
  • 3
  • 13
  • Is ValueRange not just an example? It only appears in that context, it's not documented in its own right. – jonrsharpe Dec 20 '20 at 22:49
  • You might be right. I couldn't find any example declaration so assumed it was something in the stdlib. So the constraints are dynamic? If so how would I go about declaring those on my own? Alternatively, how could I annotate constraints to the size/values of a list in some other way? – Jonathan Levin Dec 20 '20 at 22:59
  • 1
    The point of the example is that it's *not* defined, the second parameter is metadata and ignored in the absence of specific logic. – jonrsharpe Dec 20 '20 at 23:05
  • Well gee, I got excited too. It would be cool to see an example of a ValueRange implementation. – Ismael Harun Jul 03 '21 at 23:43
  • 1
    A full example solution has been posted in [this other question](https://stackoverflow.com/questions/68454202/how-to-use-maxlen-of-typing-annotation-of-python-3-9/68489244#68489244). – Daniel Azemar Jul 22 '21 at 17:51
  • Does this answer your question? [How to use MaxLen of typing.Annotation of python 3.9?](https://stackoverflow.com/questions/68454202/how-to-use-maxlen-of-typing-annotation-of-python-3-9) – Daniel Azemar Jul 27 '21 at 14:03

2 Answers2

2

As others have said, these classes are just an example of what can be annotated. Annotation just grabs a certain variable and adds some "hints" to them via the class you created (MaxLen, ValueRange, etc).

You can then obtain which "hints" are related to every parameter using get_type_hints, and crawl one per one the parameters with its hits and do the checks you want (not the idea Annotation was intended, though I also found it interesting). You have a full example in this other post.

Daniel Azemar
  • 478
  • 7
  • 19
1

You could define it using dataclasses.dataclass:

from dataclasses import dataclass

@dataclass
class ValueRange:
    min: float
    max: float

or alternatively using collections.namedtuple:

from collections import namedtuple

ValueRange = namedtuple("ValueRange", ["min", "max"])
jrc
  • 20,354
  • 10
  • 69
  • 64