is it possible to configure Black to error or warn on non-literal dict instantiation or similar?

158 Views Asked by At

When enforcing code style, my team prefers using a dict literal instead of the dict() function call:

c = { "a": 1 } // good

d = {}         // good

e = dict()     // bad

Can Black (or any linter or code formatter for python) do this?

1

There are 1 best solutions below

0
On BEST ANSWER

Maintainer of black here :wave:

Black cannot do this as this would be an AST unsafe transformation. It's not certain whether Black will gain AST unsafe features down the road, but it's unlikely IMO.

Instead you can use pylint with code R1735 enabled or use flake8-comprehensions with code C408 enabled.

$ cat test.py
c = {"a": 1}  # good

d = {}          # good

e = dict()      # bad

$ flake8 test.py
test.py:5:5: C408 Unnecessary dict call - rewrite as a literal.

$ pylint test.py
************* Module test
test.py:1:0: C0114: Missing module docstring (missing-module-docstring)
test.py:5:4: R1735: Consider using {} instead of dict() (use-dict-literal)

------------------------------------------------------------------
Your code has been rated at 3.33/10 (previous run: 3.33/10, +0.00)