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

Release v2.1.0 #73

Merged
merged 12 commits into from
Apr 11, 2020
2 changes: 2 additions & 0 deletions .dependabot/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ update_configs:
dependency_name: "pytest*"
- match:
dependency_name: "tox"
- match:
dependency_name: "pep8-naming"
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Changelog
Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html) (`<major>`.`<minor>`.`<patch>`)

## [v2.1.0]
### Added
* #68 Add `--suppress-dummy-args` configuration option to suppress ANN000 level errors for dummy arguments, defined as `"_"`

## [v2.0.1]
### Added
* #71 Add `pep8-naming` to linting toolchain
Expand Down
48 changes: 25 additions & 23 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ Note that contributions may be rejected on the basis of a contributor failing to
2. If you have direct access to the repository, **create a branch for your changes** and create a pull request for that branch. If not, create a branch on a fork of the repository and create a pull request from there.
* It's common practice for a repository to reject direct pushes to `master`, so make branching a habit!
* If PRing from your own fork, **ensure that "Allow edits from maintainers" is checked**. This gives permission for maintainers to commit changes directly to your fork, speeding up the review process.
3. **Adhere to the prevailing code style**, which we enforce using [flake8](http://flake8.pycqa.org/en/latest/index.html).
* Run `flake8` against your code **before** you push it. Your commit will be rejected by the build server if it fails to lint.
* [Git Hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) are a powerful tool that can be a daunting to set up. Fortunately, [`pre-commit`](https://github.com/pre-commit/pre-commit) abstracts this process away from you and is provided as a dev dependency for this project. Run `pre-commit install` when setting up the project and you'll never have to worry about breaking the build for linting errors.
3. **Adhere to the prevailing code style**, which we enforce using [`flake8`](http://flake8.pycqa.org/en/latest/index.html), [`black`](https://black.readthedocs.io/en/stable/), and [`pre-commit`](https://pre-commit.com/).
* Run `flake8` and `pre-commit` against your code [**before** you push it](https://soundcloud.com/lemonsaurusrex/lint-before-you-push). Your commit will be rejected by the build server if it fails to lint.
* [Git Hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) are a powerful git feature for executing custom scripts when certain important git actions occur. The pre-commit hook is the first hook executed during the commit process and can be used to check the code being committed & abort the commit if issues, such as linting failures, are detected. While git hooks can seem daunting to configure, the `pre-commit` framework abstracts this process away from you and is provided as a dev dependency for this project. Run `pre-commit install` when setting up the project and you'll never have to worry about committing code that fails linting.
4. **Make great commits**. A well structured git log is key to a project's maintainability; it efficiently provides insight into when and *why* things were done for future maintainers of the project.
* Commits should be as narrow in scope as possible. Commits that span hundreds of lines across multiple unrelated functions and/or files are very hard for maintainers to follow. After about a week they'll probably be hard for you to follow too.
* Try to avoid making minor commits for fixing typos or linting errors. Since you've already set up a pre-commit hook to run `flake8` before a commit, you shouldn't be committing linting issues anyway.
* Avoid making minor commits for fixing typos or linting errors. Since you've already set up a `pre-commit` hook to run the linting pipeline before a commit, you shouldn't be committing linting issues anyway.
* A more in-depth guide to writing great commit messages can be found in Chris Beam's [*How to Write a Git Commit Message*](https://chris.beams.io/posts/git-commit/)
5. **Avoid frequent pushes to the main repository**. This goes for PRs opened against your fork as well. Our test build pipelines are triggered every time a push to the repository (or PR) is made. Try to batch your commits until you've finished working for that session, or you've reached a point where collaborators need your commits to continue their own work. This also provides you the opportunity to amend commits for minor changes rather than having to commit them on their own because you've already pushed.
* This includes merging master into your branch. Try to leave merging from master for after your PR passes review; a maintainer will bring your PR up to date before merging. Exceptions to this include: resolving merge conflicts, needing something that was pushed to master for your branch, or something was pushed to master that could potentionally affect the functionality of what you're writing.
Expand All @@ -24,11 +24,10 @@ Note that contributions may be rejected on the basis of a contributor failing to
* One option is to fork the other contributor's repository and submit your changes to their branch with your own pull request. We suggest following these guidelines when interacting with their repository as well.
* The author(s) of inactive PRs and claimed issues will be be pinged after a week of inactivity for an update. Continued inactivity may result in the issue being released back to the community and/or PR closure.
8. **Work as a team** and collaborate wherever possible. Keep things friendly and help each other out - these are shared projects and nobody likes to have their feet trodden on.
9. **Internal projects are internal**. As a contributor, you have access to information that the rest of the server does not. With this trust comes responsibility - do not release any information you have learned as a result of your contributor position. We are very strict about announcing things at specific times, and many staff members will not appreciate a disruption of the announcement schedule.
10. All static content, such as images or audio, **must be licensed for open public use**.
9. All static content, such as images or audio, **must be licensed for open public use**.
* Static content must be hosted by a service designed to do so. Failing to do so is known as "leeching" and is frowned upon, as it generates extra bandwidth costs to the host without providing benefit. It would be best if appropriately licensed content is added to the repository itself so it can be served by PyDis' infrastructure.

Above all, the needs of our community should come before the wants of an individual. Work together, build solutions to problems and try to do so in a way that people can learn from easily. Abuse of our trust may result in the loss of your Contributor role, especially in relation to Rule 9.
Above all, the needs of our community should come before the wants of an individual. Work together, build solutions to problems and try to do so in a way that people can learn from easily. Abuse of our trust may result in the loss of your Contributor role.

## Changes to this Arrangement

Expand All @@ -39,15 +38,19 @@ All projects evolve over time, and this contribution guide is no different. This
When pulling down changes from GitHub, **remember to sync your environment** using `poetry install` to ensure you're using the most up-to-date versions the project's dependencies.

### Type Hinting
[PEP 484](https://www.python.org/dev/peps/pep-0484/) formally specifies type hints for Python functions, added to the Python Standard Library in version 3.5. Type hints are recognized by most modern code editing tools and provide useful insight into both the input and output types of a function, preventing the user from having to go through the codebase to determine these types.
[PEP 484](https://www.python.org/dev/peps/pep-0484/) formally specifies type hints for Python functions, added to the Python Standard Library in version 3.5. Type hints are recognized by most modern code editing tools and provide useful insight into both the input and output types of a function, preventing the user from having to go through the codebase to determine these types.

For example:

```py
def foo(input_1: int, input_2: dict) -> bool:
import typing as t


def foo(input_1: int, input_2: t.Dict[str, str]) -> bool:
...
```

Tells us that `foo` accepts an `int` and a `dict` and returns a `bool`.
Tells us that `foo` accepts an `int` and a `dict`, with `str` keys and values, and returns a `bool`.

All function declarations should be type hinted in code contributed to the PyDis organization.

Expand All @@ -59,41 +62,40 @@ Many documentation packages provide support for automatic documentation generati
For example:

```py
def foo(bar: int, baz: dict=None) -> bool:
import typing as t


def foo(bar: int, baz: t.Optional[t.Dict[str, str]] = None) -> bool:
"""
Does some things with some stuff.

:param bar: Some input
:param baz: Optional, some other input
:param baz: Optional, some dictionary with string keys and values

:return: Some boolean
"""
...
```

Since PyDis does not utilize automatic documentation generation, use of this syntax should not be used in code contributed to the organization. Should the purpose and type of the input variables not be easily discernable from the variable name and type annotation, a prose explanation can be used. Explicit references to variables, functions, classes, etc. should be wrapped with backticks (`` ` ``).

For example, the above docstring would become:

```py
def foo(bar: int, baz: dict=None) -> bool:
import typing as t


def foo(bar: int, baz: t.Optional[t.Dict[str, str]] = None) -> bool:
"""
Does some things with some stuff.

This function takes an index, `bar` and checks for its presence in the database `baz`, passed as a dictionary. Returns `False` if `baz` is not passed.
"""
...
```

### Logging Levels
The project currently defines [`logging`](https://docs.python.org/3/library/logging.html) levels as follows:
* **TRACE:** Use this for tracing every step of a complex process. That way we can see which step of the process failed. Err on the side of verbose. **Note:** This is a PyDis-implemented logging level.
* **DEBUG:** Someone is interacting with the application, and the application is behaving as expected.
* **INFO:** Something completely ordinary happened. Like a cog loading during startup.
* **WARNING:** Someone is interacting with the application in an unexpected way or the application is responding in an unexpected way, but without causing an error.
* **ERROR:** An error that affects the specific part that is being interacted with
* **CRITICAL:** An error that affects the whole application.

### Work in Progress (WIP) PRs
Github [has introduced a new PR feature](https://github.blog/2019-02-14-introducing-draft-pull-requests/) that allows the PR author to mark it as a WIP. This provides both a visual and functional indicator that the contents of the PR are in a draft state and not yet ready for formal review.
Github [provides a PR feature](https://github.blog/2019-02-14-introducing-draft-pull-requests/) that allows the PR author to mark it as a WIP. This provides both a visual and functional indicator that the contents of the PR are in a draft state and not yet ready for formal review.

This feature should be utilized in place of the traditional method of prepending `[WIP]` to the PR title.

Expand Down
24 changes: 18 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ You can verify it's being picked up by invoking the following in your shell:

```bash
$ flake8 --version
3.7.8 (flake8-annotations: 2.0.1, mccabe: 0.6.1, pycodestyle: 2.5.0, pyflakes: 2.1.1) CPython 3.7.4 on Darwin
3.7.8 (flake8-annotations: 2.1.0, mccabe: 0.6.1, pycodestyle: 2.5.0, pyflakes: 2.1.1) CPython 3.7.4 on Darwin
```

## Table of Warnings
All warnings are enabled by default.

### Function Annotations
| ID | Description |
|----------|-----------------------------------------------|
Expand All @@ -35,10 +37,10 @@ $ flake8 --version
| `ANN003` | Missing type annotation for `**kwargs` |

### Method Annotations
| ID | Description |
|----------|----------------------------------------------------|
| `ANN101` | Missing type annotation for `self` in method |
| `ANN102` | Missing type annotation for `cls` in classmethod |
| ID | Description |
|----------|--------------------------------------------------------------|
| `ANN101` | Missing type annotation for `self` in method<sup>1</sup> |
| `ANN102` | Missing type annotation for `cls` in classmethod<sup>1</sup> |

### Return Annotations
| ID | Description |
Expand All @@ -55,15 +57,25 @@ $ flake8 --version
|----------|-----------------------------------------------------------|
| `ANN301` | PEP 484 disallows both type annotations and type comments |

**Notes:**
1. See: [PEP 484](https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods) and [PEP 563](https://www.python.org/dev/peps/pep-0563/) for suggestions on annotating `self` and `cls` arguments.


## Configuration Options
Some opinionated flags are provided to tailor the linting errors emitted:

### `--suppress-none-returning`: `bool`
Suppress `ANN200`-level errors for functions that meet one of the following criteria:
* Contain no `return` statement, or
* Explicit `return` statement(s) all return `None` (explicitly or implicitly).

Default: `False`

### `--suppress-dummy-args`: `bool`
Suppress `ANN000`-level errors for dummy arguments, defined as `_`.

Default: `False`


## Caveats for PEP 484-style Type Comments
### Function type comments
Expand Down Expand Up @@ -92,7 +104,7 @@ def foo(
pass
```

Ellipes are ignored by `flake8-annotations` parser.
Ellipses are ignored by `flake8-annotations` parser.

**Note:** If present, function type comments will override any argument type comments.

Expand Down
18 changes: 16 additions & 2 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ jobs:
PIP_CACHE_DIR: ".cache/pip"
PIP_SRC: ".cache/src"
POETRY_VIRTUALENVS_CREATE: false
PRE_COMMIT_HOME: $(Pipeline.Workspace)/pre-commit-cache

steps:
- task: UsePythonVersion@0
displayName: 'Set Python version'
name: PythonVersion
inputs:
versionSpec: '$(python.version)'
addToPath: true
Expand All @@ -35,8 +37,20 @@ jobs:
- script: python3 -m pip install poetry && poetry install
displayName: 'Install Project Environment'

- script: flake8
displayName: 'Lint flake8-annotations'
- task: Cache@2
displayName: 'Restore pre-commit environment'
condition: and(succeeded(), eq(variables['python.version'], '3.8'))
inputs:
key: pre-commit | "$(PythonVersion.pythonLocation)" | .pre-commit-config.yaml
restoreKeys: |
pre-commit | "$(PythonVersion.pythonLocation)"
MarkKoz marked this conversation as resolved.
Show resolved Hide resolved
path: $(PRE_COMMIT_HOME)

# This will also take care of linting, as we utilize a flake8 hook
# Only run this in one python environment
- script: pre-commit run --all-files
condition: and(succeeded(), eq(variables['python.version'], '3.8'))
displayName: 'Run pre-commit hooks'

- script: tox -e $(tox.env)
displayName: 'Test & generate coverage'
Expand Down
2 changes: 1 addition & 1 deletion flake8_annotations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

PY_GTE_38 = False

__version__ = "2.0.1"
__version__ = "2.1.0"

AST_ARG_TYPES = ("args", "vararg", "kwonlyargs", "kwarg")
if PY_GTE_38:
Expand Down
23 changes: 21 additions & 2 deletions flake8_annotations/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ def __init__(self, tree: ast.Module, lines: List[str]):
# Request `lines` here and join to allow for correct handling of input from stdin
self.lines = lines
self.tree = self.get_typed_tree("".join(lines)) # flake8 doesn't strip newlines
self.suppress_none_returning: bool # Set by flake8's config parser

# Set by flake8's config parser
self.suppress_none_returning: bool
self.suppress_dummy_args: bool

def run(self) -> Generator[FORMATTED_ERROR, None, None]:
"""
Expand Down Expand Up @@ -75,12 +78,17 @@ def run(self) -> Generator[FORMATTED_ERROR, None, None]:

# Yield explicit errors for arguments that are missing annotations
for arg in function.get_missed_annotations():
# Skip yielding return errors if the `--suppress-none-returning` flag is True and
# Skip yielding return errors if the `--suppress-none-returning` flag is `True` and
# the function has only `None` returns (which includes the case of no returns)
if arg.argname == "return" and self.suppress_none_returning:
if not arg.has_type_annotation and function.has_only_none_returns:
continue

# If the `--suppress-dummy-args` flag is `True`, skip yielding errors for any
# arguments named `_`
if arg.argname == "_" and self.suppress_dummy_args:
continue

yield classify_error(function, arg).to_flake8()

@classmethod
Expand All @@ -97,10 +105,21 @@ def add_options(cls, parser: OptionManager) -> None:
),
)

parser.add_option(
"--suppress-dummy-args",
default=False,
action="store_true",
parse_from_config=True,
help=(
"Suppress ANN000-level errors for dummy arguments, defined as '_'. (Default: False)"
),
)

@classmethod
def parse_options(cls, options: Namespace) -> None:
"""Parse the custom configuration options given to flake8."""
cls.suppress_none_returning = options.suppress_none_returning
cls.suppress_dummy_args = options.suppress_dummy_args

@staticmethod
def get_typed_tree(src: str) -> ast.Module:
Expand Down
Loading