Skip to content
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

Treat annotations more opaquely (proposal) #6147

Closed
valtron opened this issue Jan 5, 2019 · 2 comments
Closed

Treat annotations more opaquely (proposal) #6147

valtron opened this issue Jan 5, 2019 · 2 comments

Comments

@valtron
Copy link

valtron commented Jan 5, 2019

Python allows annotations to be any expression, but if you use MyPy on your project, you can't use annotations for anything other than types (MyPy will error "Invalid type ...").

This issue proposes the following solution:

  • provide class typing.Annot (name for the purposes of this discussion):
class Annot:
    def __init__(self, type_=None, **kwargs):
        self.type = type_
        self.kwargs = kwargs
  • during typechecking, MyPy treats annotations that are instances of Annot as if they were their type property

Benefits/Use cases

MyPy/other tools (including runtime inspection) also have extra info in kwargs available, if they know how to use it. For example, dataclasses (and attrs, and this concept) store extra field information in the value of the attribute:

@dataclass
class C:
    z: int = field(repr=False, default=10)

...which is a workaround. With general-purpose annotations, it could look like this:

@dataclass
class C:
    z: Annot(int, repr=False, default=10)

This could also subsume class attribute annotations and Final annotations:

class A:
    x: Annot(int, classvar=True) = 0
    y: Annot(final=True) = ''

But the main benefit is that with this in place, it will be possible to add annotations as well as, or instead of, plain type info, without foregoing MyPy, paving the way for more tooling.

@Michael0x2a
Copy link
Collaborator

You may be interested in this proposal in the "typing" github repo, which proposes an idea similar to yours.

@ilevkivskyi
Copy link
Member

I think this is essentially a duplicate of python/typing#600, we can continue discussing details in that issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants