Skip to content

auto-optional

Logo

auto-optional: adds the Optional type-hint to arguments where the default value is None

actions batch pypi python versions codecov License: MIT Code style: black


Documentation: auto-optional.daanluttik.nl

Source Code: github.com/luttik/auto-optional


What does auto-optional do

The basic purpose of auto-optional is ensuring that whenever a default argument is None the type annotation is Optional.

For example:

def foo(bar: str = None):
    ...

Would turn into

from typing import Optional
def foo(bar: Optional[str] = None):
    ...

Why would you want this

  • Easily modify external libraries that didn't pay attention to proper use of optional to improve mypy linting.
  • Force consistency in your own code-base: Enforcing that None parameter implies an Optional type.
  • Explicit is better than implicit — pep 20

In the media:

auto-optional was covered on PythonBytes #251

I love these little tools that you can run against your code that will just reformat them to be better.

— Michael Kennedy

Install

Install with pip install auto-optional.

Run

After installing you can run auto-optional usingauto-optional [paths...] (if no path is provided it'll process the current working directory).

pre-commit

You can run auto-optional via pre-commit. Add the following text to your repositories .pre-commit-config.yaml:

repos:
- repo: https://github.com/luttik/auto-optional
  rev: v0.2.0 # The version of auto-optional to use
  hooks:
  - id: auto-optional

Things of note

Things that are handled well

  • The alternatives to Optional are supported, that means both;
    • Union[X, None]
    • x | None (allowed since python 3.10+).
  • Existing imports are reused.
    • import as and from typing import ... statements are properly handled.

Things that need improvement

For all these points you can leave a thumbs-up if you want it. Also, I welcome pull-requests for these issues.

  • There is no exclude (for file patterns) option yet [#2]
  • There is no ignore (for code lines) option yet [#3]
  • Code is aways read and written as UTF-8 (which is accurate most of the time). [#4]
  • There is no diff or check command yet for a dry-run or linting. [#5]