Skip to content

Replace comments with string literals #46

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

Closed
wants to merge 2 commits into from

Conversation

flying-sheep
Copy link

As outlined in #35, both assert isinstance(…) and syntactically relevant comments have severe drawbacks.

Parallel to docstrings, using string literals for inline type hinting provides hints that eliminate those disadvantages:

  1. they appear in the standard Python AST and are therefore easier to retrieve (no 3rd party AST necessary)
  2. no significant runtime cost (like assert isinstance(…) or Undefined(…) have)
  3. equally lightweight syntax as comments (triple quouted or single quoted string literals instead of comment)

Also they are already used in e.g. PyCharm’s type hinting.

Open question: Do we prefer

'''type: List[Employee]'''
x = []

or

'type: List[Employee]'
x = []

@gvanrossum
Copy link
Member

It's a clever hack. However it takes up an extra line, whereas the # type: ... comment goes on the same line. I think PyCharm would be quite happy to switch to PEP 484 type comments (it's written in Java so I presume they have their own "forgiving" parser anyways). @JukkaL or @ambv, any comments on this proposal?

@gvanrossum
Copy link
Member

Please don't submit PRs for ideas still under active discussion.

@gvanrossum gvanrossum closed this Jan 17, 2015
@flying-sheep
Copy link
Author

Please don't submit PRs for ideas still under active discussion.

oh, sorry, i didn’t know about this policy

@JukkaL
Copy link
Contributor

JukkaL commented Jan 17, 2015

I don't really like this proposal, because a type annotation will take an extra line and it's less obviously related to the variable, so it doesn't read as well in my opinion. Using Undefined(...) is almost as concise, at least for short variable names, though it's less efficient:

'type: List[Employee]'
# vs
x = Undefined(List[Employee])
x = []

Mypy allows Undefined with a string literal argument. This way it's a little more efficient when using complex types and it would still be there in the AST. For example:

x = Undefined('List[Employee]')
x = []

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

Successfully merging this pull request may close these issues.

3 participants