question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use function annotation syntax for Type Hints.

See original GitHub issue

After dropping Python 2.7 support at #710, we can define type hints with function annotation syntax. Do you have a plan to update the coding style guideline? https://github.com/optuna/optuna/wiki/Coding-Style-Conventions

Progress

  • optuna/integration/sklearn.py (#1735)
  • optuna/study.py - assigned to harpy

Note to the questioner

We still cannot use variable annotation syntax introduced by PEP 526 because we supports Python 3.5.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:20 (19 by maintainers)

github_iconTop GitHub Comments

5reactions
c-batacommented, Aug 30, 2020

I executed @harupy’s script at latest master branch, then found no modules.

$ python check_type_hints.py
$

Thank you all for your great contribution 🎉

3reactions
harupycommented, Sep 1, 2020

A new script to detect type comments on variables (e.g. foo = "foo" # type: str). Feel free to use this when python 3.5 support has been removed.

code
import argparse
import ast
import os
import sys

from typing import Iterable, List


def iter_python_scripts(directory: str) -> Iterable[str]:
    """Yield all python scripts in the given directory"""
    for root, _, files in os.walk(directory):
        for f in files:
            if f.endswith(".py"):
                yield os.path.join(root, f)


def read_file(path: str) -> str:
    """Read a file and return its content"""
    with open(path, encoding="utf-8") as f:
        return f.read()


def has_type_comment(node: ast.AST) -> bool:
    """Return True if the given node has a type comment"""
    return hasattr(node, "type_comment") and node.type_comment is not None


def create_position_link(path: str, lineno: int, col_offset: int) -> str:
    """Create a link to the specified position"""
    return f"{path}:{lineno}:{col_offset}"


class TypeCommentVisitor(ast.NodeVisitor):
    """Find type-commented assignment statements"""

    def __init__(self) -> None:
        super().__init__()
        self.assignments: List[ast.Assign] = []

    def visit_Assign(self, node: ast.Assign) -> None:
        if has_type_comment(node):
            self.assignments.append(node)
        self.generic_visit(node)


def parse_args() -> argparse.Namespace:
    """Parse commad line arguments"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-s",
        "--show-positions",
        action="store_true",
        help="show the positions of assignment statements containing a type comment",
    )
    return parser.parse_args()


def main() -> None:
    if sys.version_info[:2] < (3, 8):
        raise Exception(
            "This script throws in Python < 3.8 "
            "because `ast.parse` doesn't support the `type_comments` argument in Python < 3.8 "
            "See: https://docs.python.org/3/library/ast.html#ast.parse"
        )

    args = parse_args()

    for d in ["optuna", "tests"]:
        for path in iter_python_scripts(d):
            src = read_file(path)
            root = ast.parse(src, type_comments=True)
            tcv = TypeCommentVisitor()
            tcv.visit(root)

            if len(tcv.assignments) == 0:
                continue

            if args.show_positions:
                print(
                    "\n".join(
                        create_position_link(path, t.lineno, t.col_offset) for t in tcv.assignments
                    )
                )
            else:
                print(path)


if __name__ == "__main__":
    main()

How to run:

python check_type_comments.py
python check_type_comments.py --show-positions
Read more comments on GitHub >

github_iconTop Results From Across the Web

typing — Support for type hints — Python 3.11.1 documentation
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers,...
Read more >
Type hints cheat sheet - mypy 0.991 documentation
Type hints cheat sheet#. This document is a quick cheat sheet showing how to use type annotations for various common types in Python....
Read more >
Understanding type annotation in Python - LogRocket Blog
With type hints, you can annotate variables and functions with datatypes. ... define a variable with a type hint using the following syntax:...
Read more >
Type Hinting - Real Python
Use spaces around the = sign when combining an argument annotation with a default value ( align: bool = True ). Use spaces...
Read more >
How can I specify the function type in my type hints?
No you cannot, when running mypy , this gives the error: error: Invalid type comment or annotation note: Suggestion: use type[...] instead of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found