MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
186 stars 19 forks source link

[SIM907] Use Optional[Type] instead of Union[Type, None] #64

Closed kasium closed 2 years ago

kasium commented 3 years ago

Explanation

Sometimes people tend to write Union[Type, None] instead of Optional[Type].

Example

# Bad
def foo(a: Union[int, None]) -> Union[int, None]:
  return a

# Good
def foo(a: Optional[int]) -> Optional[int]:
  return a
MartinThoma commented 2 years ago
$ astpretty --no-show-offsets /dev/stdin <<< `cat example.py`
Module(
    body=[
        FunctionDef(
            name='foo',
            args=arguments(
                posonlyargs=[],
                args=[
                    arg(
                        arg='a',
                        annotation=Subscript(
                            value=Name(id='Union', ctx=Load()),
                            slice=Tuple(
                                elts=[
                                    Name(id='int', ctx=Load()),
                                    Constant(value=None, kind=None),
                                ],
                                ctx=Load(),
                            ),
                            ctx=Load(),
                        ),
                        type_comment=None,
                    ),
                ],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=[],
                kwarg=None,
                defaults=[],
            ),
            body=[
                Return(
                    value=Name(id='a', ctx=Load()),
                ),
            ],
            decorator_list=[],
            returns=Subscript(
                value=Name(id='Union', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Name(id='int', ctx=Load()),
                        Constant(value=None, kind=None),
                    ],
                    ctx=Load(),
                ),
                ctx=Load(),
            ),
            type_comment=None,
        ),
    ],
    type_ignores=[],
)
Skylion007 commented 2 years ago

Note: in 3.10+ PyUpgrade recommends using Type | None which translates to Union[Type, None] as this shorthand is shorter than Optional[Type] , so I wonder how useful this check would actually be.

MartinThoma commented 2 years ago

Thank you! I'll try to find a way to disable it for Python 3.10+ :-) (should be possible with sys.version)