-
Notifications
You must be signed in to change notification settings - Fork 242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow creating type aliases with type checked metadata attached #555
Comments
To be clear, I'm not expecting MyPy to do anything with the metadata other than type check the metadata object itself. |
This is essentially fixed with PEP 593, |
@ilevkivskyi I just saw this got closed. This is great news. Question though, is it possible yet to create something like |
The currently supported syntax is a bit more verbose, but I think this is possible. For example: from typing_extensions import Annotated as An
def get_rough_birth_year(age: An[int, Range(min=0, max=120)]):
return datetime.today().year - age The problem with the original proposal is that it is hard to define a general enough API/syntax for user-defined annotations. |
@ilevkivskyi That makes sense. The part that is missing that would be really valuable as a library creator would be to be able to define and export strictly typed annotation types (if that makes sense). In your example the user could pass in something other than Range(...), and the type checker wouldn't care. What if you could define a generic annotation type like this: MinMaxOptions = TypedDict('MinMaxOptions', {'min': int, 'max': int})
def Range(min: int, max: int) -> MinMaxOptions:
return {'min': min, 'max': max}
MinMaxInt = GenericAnnotation[int, MinMaxOptions]
def get_rough_birth_year(age: MinMaxInt[Range(min=0, max=120)]):
return datetime.today().year - age With that the shape of the annotation could be anything, but once defined could be enforced. Or am I still missing something? |
Yes, this is something that goes beyond PEP 593. But it is also a harder sale. Anyway, let's re-open to track this particular case. |
Annotations in Python have many use cases beyond static type checking. I'd really like to be able to create a type that is an alias to another type while also attaching metadata to it. The idea is to be able to use MyPy's type system but also use annotations for other use cases such as runtime validation at the same time. I'm thinking something along these lines (though I have no idea how this would work in practice):
The text was updated successfully, but these errors were encountered: